Issue
If I have two activities in my app, one with listview and the other with mapview and they both use the same data (the first one shows the list, the other shows pins on a map) should I use IntentService to provide the data to both of them? If so, should I rather use the started service or bound service approach?
Solution
You can bind your Activities to a Service, see http://developer.android.com/reference/android/app/Service.html.
Create an implementation of the Binder
interface in your Service
, e.g.
public class ServiceBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
In your Activity, create a new ServiceConnection
class which will be used to give you access to your Service:
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mMyService = ((MyService.ServiceBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mMyService = null;
}
};
Here the member variable mMyService
will give you access to all public members of your Service class.
To create the connection, implement doBindService
and doUnbindService
in your Activity:
void doBindService() {
bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
}
void doUnbindService() {
// Detach our existing connection.
unbindService(mConnection);
}
Hope this helps!
Answered By - Lukas Batteau
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.