Android Service example

In this Android tip, I will give you an example of using Service in Android to download a file from internet. Service is an Android component that can be used to do a long-run task. The Service continues to run in background even if the user switches to other applications or closes the application that starts the Service.


Now to have a workable example application to use Android Service to download a file from internet, you need to create a new Android project. Then modify the activity_main.xml file to add one EditText, one Button, and a TextView as shown below. The EditText allows user to input the address of the file. The Button is pushed to start the downloading service. The TextView display status message "Please wait...", "Complete", or "Can't download the file". When you click the Button, the TextView displays "Please wait..." message. After the download task completes, it shows the "Complete" message. If there is any problem in downloading the file it shows the "Can't download the file" message.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
   android:orientation="vertical"
   >

   <EditText
     android:id="@+id/txt_filename"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:hint="Enter file url" />
   <Button
     android:id="@+id/bt_download"
     android:text="Download"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:onClick="download"
     />
   <TextView
     android:id="@+id/txt_status"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
  />

</LinearLayout>



Then create a class called DownloadService that extends the IntentService class. In the onHandleIntent method, the code is written to receive the file url sent from the MainActivity and invokes the downloadFile method to download the file. After the download task completes, the sendMessage method is invoked to send the message back to the MainActivity to update the message displayed on the TextView.

DownloadService.java

  package com.example.serviceexample;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

public class DownloadService extends IntentService {
public static final String FILEURL="FILEURL";
private String feedback="";
private String storeDir="";
public DownloadService () {
super("SERVICE");
// TODO Auto-generated constructor stub
}

public void onHandleIntent(Intent intent){
//receive file url sent from the MainAcivity
Bundle b=intent.getExtras();
String fileurl="";
if(b!=null){
fileurl=b.getString(FILEURL);
if(createStoreDir()!=null)
downloadFile(fileurl);
else{
//send feedback message to the broadcast receiver
sendMessage();
}

}


}

public String createStoreDir(){
storeDir=Environment.getExternalStorageDirectory()+"/edoc_download";
File f=new File(storeDir);
if(!f.exists())
   if(!f.mkdir()){
      Log.e("Error","Can't create edoc_download directory");
      return null;
    }
    else
   return storeDir;
  else
  return storeDir;
  }

public void downloadFile(String furl){
URL url;
int count;
try {


url = new URL(furl);
String outpath="";
try {

File f=new File(storeDir);
if(f.exists()){
HttpURLConnection con=(HttpURLConnection)url.openConnection();
InputStream is=con.getInputStream();
String fullpath=url.getPath();
String filename=fullpath.substring(fullpath.lastIndexOf('/')+1);
outpath=storeDir+"/"+filename;
FileOutputStream fos=new FileOutputStream(outpath);
byte data[] = new byte[1024];   
while ((count = is.read(data)) != -1) {
fos.write(data, 0, count);
}

is.close();
fos.flush();
fos.close();
feedback="Complete";

}
else{
Log.e("Error","Not found: "+storeDir);

}

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

}catch (MalformedURLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
//send feedback message to the broadcast receiver
sendMessage();


}

public void sendMessage(){
if(feedback.length()<=0)
feedback="Can't download the file";
Intent backIntent=new Intent("com.example.serviceexample");
backIntent.putExtra("BACKMESS", feedback);
sendBroadcast(backIntent);
}

}


In the MainActivity, you will create an instance of BroadcastReceiver. The onReceive of BroadcastReceiver lets you receive the intent object sent from the download service. In this method, you update the status message on the TextView. In the onResume method, you register the broadcast receiver and in the onPause method, you unregister the receiver. The download method is called to start the download service when you click the Download button.

MainActivity.java

  package com.example.serviceexample;

import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//create BroadcastReceiver to receive Intent object from service
private BroadcastReceiver ReceiverDownload=new BroadcastReceiver(){
   public void onReceive(Context context,Intent intent){
   //Toast.makeText(context, "Receive",Toast.LENGTH_SHORT).show();
      Bundle b=intent.getExtras();
      if(b!=null){
      TextView tv=(TextView)findViewById(R.id.txt_status);
      tv.setText(b.getString("BACKMESS"));
      }
   }
   };
  
   public void download(View view){
   TextView tv=(TextView)findViewById(R.id.txt_status);
   EditText et=(EditText)findViewById(R.id.txt_filename);
   String txtpath=et.getText().toString();
   if(txtpath.length()>0){
   try{
   tv.setText("Please wait...");
   //create intent object and set it to the extracting service object
   Intent newIntent=new Intent(this,DownloadService.class);
   newIntent.putExtra(ExtractService.FILEURL,txtpath);
   startService(newIntent);
   }
   catch(Exception e){
   Toast.makeText(this, "Error in downloading the file",Toast.LENGTH_SHORT).show();
   }
   }
   else{
   Toast.makeText(this, "No filename input",Toast.LENGTH_SHORT).show();
    
   }

   }

  
  
   public void onResume(){
   super.onResume();
   //register the broadcast receiver to receive intent
   registerReceiver(ReceiverDownload, new IntentFilter("com.example.serviceexample"));

   }
  
   protected void onPause(){
   super.onPause();
   //unregister the broadcast receiver
   unregisterReceiver(ReceiverDownload);
  
   }



}


Before running the example application, you need to add permissions to use external storage and internet, and declare Service in AndroidManifest.xml file as shown below.

AndroidMainfest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.serviceexample"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
     android:minSdkVersion="8"
     android:targetSdkVersion="17" />
   <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

   <application
     android:allowBackup="true"
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name"
     android:theme="@style/AppTheme" >
     <activity
        android:name="com.example.serviceexample.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
           <action android:name="android.intent.action.MAIN" />

           <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
     </activity>
     <service
android:name="DownloadService"
android:icon="@drawable/ic_launcher"
android:label="MYSERVICE">
</service>
    
   </application>

</manifest>


Android-Service-example

Posted by: Dara | post date: 07-30-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.