I couldn\'t find any examples of how to send messages between an activity and a service, and I have spent far too many hours figuring this out. Here is an example project fo
Great tutorial, fantastic presentation. Neat, simple, short and very explanatory.
Although, notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);
method is no more. As trante stated here, good approach would be:
private static final int NOTIFICATION_ID = 45349;
private void showNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Notification Title")
.setContentText("Something interesting happened");
Intent targetIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
_nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
_nManager.notify(NOTIFICATION_ID, builder.build());
}
@Override
public void onDestroy() {
super.onDestroy();
if (_timer != null) {_timer.cancel();}
_counter=0;
_nManager.cancel(NOTIFICATION_ID); // Cancel the persistent notification.
Log.i("PlaybackService", "Service Stopped.");
_isRunning = false;
}
Checked myself, everything works like a charm (activity and service names may differ from original).
Look at the LocalService example.
Your Service
returns an instance of itself to consumers who call onBind
. Then you can directly interact with the service, e.g. registering your own listener interface with the service, so that you can get callbacks.
Seems to me you could've saved some memory by declaring your activity with "implements Handler.Callback"
Everything is fine.Good example of activity/service
communication using Messenger.
One comment : the method MyService.isRunning()
is not required.. bindService()
can be done any number of times. no harm in that.
If MyService is running in a different process then the static function MyService.isRunning()
will always return false. So there is no need of this function.
I have seen all answers. I want tell most robust way now a day. That will make you communicate between Activity - Service - Dialog - Fragments
(Everything).
EventBus
This lib which i am using in my projects has great features related to messaging.
EventBus in 3 steps
Define events:
public static class MessageEvent { /* Additional fields if needed */ }
Prepare subscribers:
Declare and annotate your subscribing method, optionally specify a thread mode:
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
Post events:
EventBus.getDefault().post(new MessageEvent());
Just add this dependency in your app level gradle
compile 'org.greenrobot:eventbus:3.1.1'
This is how I implemeted Activity->Service Communication: on my Activity i had
private static class MyResultReciever extends ResultReceiver {
/**
* Create a new ResultReceive to receive results. Your
* {@link #onReceiveResult} method will be called from the thread running
* <var>handler</var> if given, or from an arbitrary thread if null.
*
* @param handler
*/
public MyResultReciever(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == 100) {
//dostuff
}
}
And then I used this to start my Service
protected void onCreate(Bundle savedInstanceState) {
MyResultReciever resultReciever = new MyResultReciever(handler);
service = new Intent(this, MyService.class);
service.putExtra("receiver", resultReciever);
startService(service);
}
In my Service i had
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null)
resultReceiver = intent.getParcelableExtra("receiver");
return Service.START_STICKY;
}
Hope this Helps