Android bound service
- bound service is started by calling bindService.
- bound service doesn’t have an UI and it also running on the UI thread like a regular service.
- bound service will stop when no components are binded to it anymore.
- bound service can have multiple components bind to it.
- bound service has components such as activity bind to it through a ServiceConnection, and use it to for communication.
- bound service need an custom class which extends Binder.
Here is an example of bound service implementation in Android.
1. Create a class which extends from the Service, BoundService.java
public class BoundService extends Service {
private static String LOG_TAG = "BoundService";
private IBinder mBinder;
private Random mGenerator;
@Override
public void onCreate() {
super.onCreate();
Log.v(LOG_TAG, "in onCreate");
mBinder = new LocalBinder();
mGenerator = new Random();
}
@Override
public IBinder onBind(Intent intent) {
Log.v(LOG_TAG, "in onBind");
return mBinder;
}
@Override
public void onRebind(Intent intent) {
Log.v(LOG_TAG, "in onRebind");
super.onRebind(intent);
}
@Override
public boolean onUnbind(Intent intent) {
Log.v(LOG_TAG, "in onUnbind");
return true;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.v(LOG_TAG, "in onDestroy");
mGenerator = null;
}
public String getRandomNum() {
return "Random Number: " + mGenerator.nextInt(10000);
}
public class LocalBinder extends Binder {
BoundService getService() {
return BoundService.this;
}
}
}
2. Register it in the manifest.xml file in the application tag.
3. Add the following in an Activity class. Assume the method boundService responds to a button click.
BoundService mboundService;
boolean mBound = false;
public void boundService(View view) {
String randomNum = mboundService.getRandomNum();
Log.d("boundService", randomNum);
Toast.makeText(this, randomNum, Toast.LENGTH_SHORT).show();
}
@Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, BoundService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
BoundService.LocalBinder binder = (BoundService.LocalBinder) service;
mboundService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts