I have a network service that runs in the background. I have this global variable mConnectioninside Activity
protected ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
serviceobject = ((NetworkService.MyBinder) binder).getService();
}
public void onServiceDisconnected(ComponentName className) {
serviceobject = null;
}
};
and then I bind the service in Activity onCreate(..)using
bindService(new Intent(this, NetworkService.class),
mConnection,Context.BIND_AUTO_CREATE);
The NetworkService class has an inner class MyBinder
public class MyBinder extends Binder {
NetworkService getService() {
return NetworkService.this;
}
}
Now, to call any service method from Activity, I use serviceobject, and I create AsyncTaskfor each method call. (I know that calling service methods from Activity will invalidate the use of services. This is for lightweight methods that don't require a lot of computation)
This helps me directly process data from Serviceusing serviceobject. I untie the service inActivity onDestroy()
@Override
protected void onDestroy()
{
unbindService(mConnection);
super.onDestroy();
}
Is this the best way to do this, or am I mistaken somewhere?