Android IntentServce download progress

IntentService

The Service runs in background but it is on Main Thread. It is for short time consuming tasks. If you need to perform long tasks, you must use a separated thread within the Service. In contrast, The IntentSerivce runs on a separate thread. The IntentService can be used in long tasks usually with no communication to Main Thread. However, if communication required, you can use ResultReceiver or Broadcast Intents. The IntentService stops the service after all start requests have been handled.

Example: In this example we are going to create a simple file downloader with showing progress using IntentService and ResultReceiver.
- Now create a new project in Android Studio. Name the project as DownloadProgressIntentService.
- Create a new IntentService (File->New->Service->IntentService). Name the Service as DownloadIntentService. In the DownloadIntentService class, you write code to do file download and send progress to the MainActivity class. Here is the code.


 



import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.ResultReceiver;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class UploadIntentService extends IntentService {
ResultReceiver resultReceiver;

public UploadIntentService() {
  super("UploadIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {
  resultReceiver = intent.getParcelableExtra("receiver");
  if (intent != null && intent.getAction().equals(MainActivity.DOWNLOAD_ACTION)) {

   URL url;
   int count;
   HttpURLConnection con;
   InputStream is = null;
   FileOutputStream fos = null;
   try {
      url = new URL("https://www.tutorialspoint.com/ios/ios_tutorial.pdf");
     try {
       // Open connection
        con = (HttpURLConnection) url.openConnection();
       // read stream
       is = con.getInputStream();
       String pathr = url.getPath();
       // output file path
       String filename = pathr.substring(pathr.lastIndexOf('/') + 1);
       String path = Environment.getExternalStorageDirectory() + "/edoc_download/" + filename;
       //write to file
       fos = new FileOutputStream(path);
       int lenghtOfFile = con.getContentLength();
       byte data[] = new byte[1024];
       Bundle b = new Bundle();
       long total=0;
       while ((count = is.read(data)) != -1) {
           total+=count;
           // write data to file
           fos.write(data, 0, count);
           // send progress to MainActiivty through ResultReceiver
           b.putString("progress", (int)((total*100)/lenghtOfFile)+"");
          resultReceiver.send(MainActivity.RESULT_CODE, b);
       }
       fos.flush();


    } catch (Exception e) {
      e.printStackTrace();

    } finally {
     if (is != null)
     try {
        is.close();
     } catch (IOException e) {
   // TODO Auto-generated catch block
    e.printStackTrace();
   }
   if (fos != null)
     try {
      fos.close();
       } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }

   } catch (MalformedURLException e) {
// TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 }
}
  	 				
 


- - In the activity_main.xml file, you add one TextView and a ProgressBar to display progress of the download task.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android= "http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width= "match_parent"
android:layout_height= "match_parent"
android:paddingLeft= "@dimen/activity_horizontal_margin"
android:paddingRight= "@dimen/activity_horizontal_margin"
android:paddingTop= "@dimen/activity_vertical_margin"
android:paddingBottom= "@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context= "com.example.dara.myapplication1.MainActivity">

<TextView
   android:id="@+id/txtstatus"
   android:layout_width="match_parent"
   android:gravity="center"
   android:layout_height="wrap_content" />
<ProgressBar
   android:id="@+id/progress"
   style="?android:attr/progressBarStyleHorizontal"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_gravity="center_horizontal"​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​   android:max="100"
​​​​​​​​​​​​​​​​​​​​​​​​​​​​   android:paddingLeft="10sp"
​​​​​​​​​​​​​​​​​​​​​​​​​​​   android:paddingRight="10dp"
​​​​​​​​​​​​​​​​​​​​​​​​​​​   android:paddingTop="10dp"
​​​​​​​​​​​​​​​​​​​​​​​​​​   android:progress="1"
​​​​​​​​​​​​​​​​​​​​​​​​​​   android:visibility="gone"

/>

</LinearLayout>
- In the MainActivity class, you have to start the download service using the startService() method passing an Intent object in which you put a ResultReceiver object. 


import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.ResultReceiver;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import static android.os.Build.VERSION_CODES.M;

public class MainActivity extends AppCompatActivity {
​​​​​private TextView textView;
private ProgressBar progressbar;
public static String DOWNLOAD_ACTION="com.example.dara.downloadprogressintentservice.action";
​​public static int RESULT_CODE=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  if (Build.VERSION.SDK_INT >= M) {
​    ActivityCompat.requestPermissions(this,
    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
    Manifest.permission.INTERNET, Manifest.permission.ACCESS_WIFI_STATE,
    Manifest.permission.READ_EXTERNAL_STORAGE }
    , 1);
  }
   progressbar = (ProgressBar) findViewById(R.id.progress);
   progressbar.setIndeterminate(false);
   textView=(TextView)findViewById(R.id.txtstatus);

}

protected void onStart(){
   super.onStart();
   progressbar.setProgress(0);
   progressbar.setVisibility(ProgressBar.VISIBLE);
   Intent intent = new Intent(this, UploadIntentService.class);
   intent.setAction(DOWNLOAD_ACTION);
   intent.putExtra("receiver",new MyResultReceiver(new Handler()));
   startService(intent);
}

class MyResultReceiver extends ResultReceiver {
​public MyResultReceiver(Handler handler) {
super(handler);
}

protected void onReceiveResult(int resultCode, Bundle resultData) {
  if(resultCode==RESULT_CODE){
    String message=resultData.getString("progress");
    textView.setText(message+"%");
    progressbar.setProgress(Integer.parseInt(message));
​     }
   }
  }
}

					
- In AndroidManifest.xml file, immediately above <application, you add internet and write_external_storage permissions.


<uses-permission android:name= "android.permission.INTERNET" />
<uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE" />

- Now let’s run the application. The download task should start now and you see the progress as shown below. 

intentservice download progress

Posted by: Dara | post date: 05-31-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.