Android bound and unbound Services Examples

Android service is a component that is used to perform operations on the background such as downloading files from or uploading files to a remote server, playing music etc. It doesn't has any UI (user interface). A service runs in the main thread of the application instance. It doesn’t create its own thread. If you want to run a long running blocking operation you should create a new thread within the service.

Unbound Service

An application component starts the service, and it would continue to run in the background, even if the original component that started it is destroyed. You will use the startService() method to start an unbound service.

unbound serice


 
Example: Using an unbound service to play a music in background.
- Create a new Project in Android Studio. Name the project as UnboundServiceExample.
- Create a service (File->New->Service). Name the service as UnboundService.



import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
public class UnboundMyService extends Service {
MediaPlayer myPlayer;
public UnboundMyService() {
}
public IBinder onBind(Intent arg0) {
  return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
  Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
  myPlayer.start();
  return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
  Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
  myPlayer = MediaPlayer.create(this, R.raw.song);
  myPlayer.setLooping(false); // Set looping

}
@Override
public void onDestroy() {
  Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
  myPlayer.stop();
  }
}
  	 				
 


- In the MainActivity class, you call startService() and stopSevice methods to start and stop the service respectively.


protected void onStart(){
  super.onStart();
  Intent intent = new Intent(this, UnboundMyService.class);
  startService(intent);
}
protected void onStop(){
  super.onStop();
  Intent intent = new Intent(this, UnboundMyService.class);
  stopService(intent);
}
- Finally, before running the example app, you need to have the song.mp3 music file in the res/raw folder.

Bound Service

An Android component may bind itself to a Service using bindService () to perform interactivity and inter process communication. When the component binding to the bound service is destroyed, the service stops.

bound serice


Example: Using a service to download file from a given URL in background.
- Create a new Project in Android Studio. Name the project as BoundServiceExample.
- Create a service (File->New->Service). Name the service as BoundService. Here is the complete code of the BoundService class.


import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.ResultReceiver;
import android.widget.Toast;
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 java.util.Calendar;
import java.util.Date;

public class BoundService extends Service {
public BoundService() {
}

private Binder binder = new LocalBinder();
public class LocalBinder extends Binder {
  BoundService getService() {
  Return BoundService.this;
  }
}
@Override
public void onCreate() {
  Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}

public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
  Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); 
  return binder;
}


public void downloadFile(final String urlStr) {
  BackTask backTask = new BackTask();
  backTask.execute(urlStr);
}


@Override
public void onDestroy() {
  Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}

// A separate process to download a file from internet
private class BackTask extends AsyncTask<String, Integer, Void> {
protected void onPreExecute() {
}

protected Void doInBackground(String... params) {
 URL url;
 int count;
 HttpURLConnection con = null;
 InputStream is = null;
 FileOutputStream fos = null;
 try {
  url = new URL(params[0]);
  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];
  while ((count = is.read(data)) != -1) {
   fos.write(data, 0, count);
   }
  fos.flush();


 } catch (Exception e) {
   e.printStackTrace();
   String error_Message = e.getMessage();
   if (error_Message != null) {
     Log.e("BoundService",error_Message);
  }

   } 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();
  }
  return null;
}

protected void onPostExecute(Void result) {
  Toast.makeText(this, "Download finished", Toast.LENGTH_LONG).show();
     }

  }
}

					
 - In the activity_main.xml file, you add a Button. The Button is pressed to download a file from a url.

<Button
android:id="@+id/btn_download"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Download"
android:onClick="downloadFile" />
/>
- 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" />

- In the onStart() method of the MainActivity class, you start the bound service using the bindService() method. You need to pass an Intent instance, a ServiceConnection instance, and a binding flag. With the intent object, you can specify the bound service to start and data to be passed to the service. The ServiceConnection object create a connection between the MainActivity and the BoundService. You can get the BoundService instance from the ServiceConnection object. As a sequence, you are able to call the downloadFile() of the bound service in the MainActivity. The BIND_AUTO_CREATE tells the system to create the service instance automatically as long as the binding exists. In the onStop() method, you call the unbindService() method to unbind the activity from the service when the activity stops.

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.File;
import java.util.Date;
import static android.os.Build.VERSION_CODES.M;
public class MainActivity extends AppCompatActivity {
BoundService myService;
boolean isBound=false; 
@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.ACCESS_NETWORK_STATE,
    Manifest.permission.READ_EXTERNAL_STORAGE
   }
, 1);
} 

}

protected void onStart(){
  super.onStart();
  Log.i("MainActivity","onStart called");
  Intent intent = new Intent(this,BoundService.class);
  //start service with binding
  bindService(intent, MyConnection, Context.BIND_AUTO_CREATE);

}

private ServiceConnection MyConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
  BoundService.LocalBinder binder=(BoundService.LocalBinder)service;
  myService=binder.getService();
  isBound=true;
}

@Override
public void onServiceDisconnected(ComponentName name) {
  isBound=false;
  }
};

public void downloadFile(View v){

// Download file 
myService.downloadFile("https://static.pexels.com/photos/4825/red-love-romantic-flowers.jpg");

}

protected void onStop(){
  super.onStop();
  Log.i("MainActivity","onStop called");
  if (isBound) {
  //unbind service 
  unbindService(MyConnection);
  isBound = false;
   } 
 }
}

 

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.