Android IntentService example

Android provides two important classes, AsyncTask and IntentService, to perform long operations (e.g. download and upload files from and to a remote server) in background in separate worker threads.  AsyncTask should be used in a case that you need to have active communication between the worker thread and the main or UI thread. For example, if you wish to publish the progress on the user interface while downloading a file from the internet, you use AsyncTask. Otherwise, you use IntentService. The service created by IntentService class is started by calling the startService(Intent intent). The IntentService handles an intent in the onHandleIntent() method. It terminates itself if it is appropriate. To communicate with the UI thread, you need a BroadcastReceiver to get the intent sent from the service.



Now to have example application on using IntentService to perform an image download task, you create a new project in Android studio. In the activity_main.xml file, you add an EditText, a Button, and a TextView.

<EditText
     android:id="@+id/txturl"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:hint="Enter image url"
     />
   <Button
     android:id="@+id/btdownload"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Download"
     android:gravity="center"
         />
   <TextView
     android:id="@+id/txtmessage"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"

     />

To create a service in Android studio, from the project tree you right-click the java directory->New->Service (IntentService). Then enter DownloadService for the class name. The DownloadService service is created and automatically registered in AndroidManifest.xml file. Here is the code written to perform file download task when the service starts.

public class DownloadService extends IntentService {
   // TODO: Rename actions, choose action names that describe tasks that this
   // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
   public static final String ACTION_DOWNLOAD = "com.example.dara.myapplication.action.DOWNLOAD";
   //public static final String ACTION_BAZ = "com.example.dara.myapplication.action.BAZ";

   // TODO: Rename parameters
   public static final String EXTRA_URL = "com.example.dara.myapplication.extra.URL";
   public static final String EXTRA_MESSAGE = "com.example.dara.myapplication.extra.message";

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

   @Override
   protected void onHandleIntent(Intent intent) {
     if (intent != null) {
        final String action = intent.getAction();
        if (ACTION_DOWNLOAD.equals(action)) {
           final String url = intent.getStringExtra(EXTRA_URL);
           Log.e("Service", url);
           downloadImage(url);
        }
     }
   }

   private void downloadImage(String urlStr){
     FileOutputStream fos=null;
     InputStream is=null;
     String message="Download failed.";
     try {
        // Get InputStream from the image url
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //connection.setDoInput(true);
        //connection.connect();
        is=connection.getInputStream();
        String fileName = urlStr.substring(urlStr.lastIndexOf('/') + 1);
        fos=new FileOutputStream(Environment.getExternalStorageDirectory()+"/"+fileName);
        byte[] buffer=new byte[1024];
        int count;
        while((count=is.read(buffer))>0){
           fos.write(buffer,0,count);
        }
           fos.flush();
        message="Download completed";


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

        if(fos!=null){
           try {
             fos.close();

           }catch(IOException e){}

        }
        if(is!=null){
           try {
             is.close();

           }catch(IOException e){}

        }
        // Send the feedback message to the MainActivity
        Intent backIntent=new Intent(DownloadService.ACTION_DOWNLOAD);
        backIntent.putExtra(DownloadService.EXTRA_MESSAGE, message);
        sendBroadcast(backIntent);
     }
   }
}

In the MainActivity class, you write code to register a BroadcastReceiver to handle feedback message from the service, and start the service.

public class MainActivity extends FragmentActivity {
   private Context context;
   private TextView tv;
   private BroadcastReceiver DownloadReceiver=new BroadcastReceiver(){
     public void onReceive(Context context,Intent intent){
        // Display message from DownloadService
        Bundle b=intent.getExtras();
        if(b!=null){

           tv.setText(b.getString(DownloadService.EXTRA_MESSAGE));
        }
     }
   };

   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     context=this;
     tv=(TextView)findViewById(R.id.txtmessage);
     Button btDownload=(Button)findViewById(R.id.btdownload);
     btDownload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           EditText url=(EditText)findViewById(R.id.txturl);
           String urlStr=url.getText().toString();
           if(!urlStr.equals("")){

             Intent newIntent=new Intent(context,DownloadService.class);
             newIntent.setAction(DownloadService.ACTION_DOWNLOAD);
             newIntent.putExtra(DownloadService.EXTRA_URL,urlStr);
             // Start Download Service
             tv.setText("Downloading...");
             context.startService(newIntent);
           }
        }
     });

     }

   protected void onResume(){
     super.onResume();
     // Register receiver to get message from DownloadService
     registerReceiver(DownloadReceiver, new IntentFilter(DownloadService.ACTION_DOWNLOAD));

   }

   protected void onPause(){
     super.onPause();
     // Unregister the receiver
     unregisterReceiver(DownloadReceiver);

   }
}

Before running the example application, do not forget to declare INTERNET and WRITE_EXTERNAL_STORAGE permissions to the AndroidManifest.xml file.

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


Android-IntentService-example

Posted by: Dara | post date: 02-22-2015 | 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.