I have a network Service which runs in the background. I have this global variable mConnection
inside the 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 the Activity's 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 invoke any Service method from the Activity, i use the serviceobject
and I create an AsyncTask
for each method invocation.(I know that invoking Service methods from the Activity nullifies the use of having Services.I use this for light methods which doesn't involve much computation)
This helps me to directly deal with the data from the Service
using the serviceobject
.
I unbind the Service in the Activity
's onDestroy()
@Override
protected void onDestroy()
{
unbindService(mConnection);
super.onDestroy();
}
Is this the best way of doing it or am I wrong somewhere?
I think what you wanna do is to run a Remote Service
. That's what ServiceConnection
and bindService
is used to. The idea is that your service runs in the baackground and any activity can "bind" to it and interact through in interface you define in AIDL.
The access to the service is fast so you can call method from your service from the UI thread without the use ofAsyncTask
. That's one benefit.
However the implementation is a bit tedious because you must write this AIDL interface.
I recommend you to read Google's tutorial here: http://developer.android.com/guide/developing/tools/aidl.html
And then to google "Remote Service AIDL" with "tutorial" or "example".
Good Luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With