Skip to content Skip to sidebar Skip to footer

Example: Communication Between Activity And Service Using Messaging

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 for others

Solution 1:

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.

Solution 2:

For sending data to a service you can use:

Intent intent = newIntent(getApplicationContext(), YourService.class);
intent.putExtra("SomeData","ItValue");
startService(intent);

And after in service in onStartCommand() get data from intent.

For sending data or event from a service to an application (for one or more activities):

privatevoidsendBroadcastMessage(String intentFilterName, int arg1, String extraKey) {
    Intent intent = newIntent(intentFilterName);
    if (arg1 != -1 && extraKey != null) {
        intent.putExtra(extraKey, arg1);
    }
    sendBroadcast(intent);
}

This method is calling from your service. You can simply send data for your Activity.

private void someTaskInYourService(){

    //For example you downloading from server 1000 filesfor(int i = 0; i < 1000; i++) {
        Thread.sleep(5000) // 5 seconds. Catch in try-catch blocksendBroadCastMessage(Events.UPDATE_DOWNLOADING_PROGRESSBAR, i,0,"up_download_progress");
    }

For receiving an event with data, create and register method registerBroadcastReceivers() in your activity:

privatevoidregisterBroadcastReceivers(){
    broadcastReceiver = newBroadcastReceiver() {
        @OverridepublicvoidonReceive(Context context, Intent intent) {
            intarg1= intent.getIntExtra("up_download_progress",0);
            progressBar.setProgress(arg1);
        }
    };
    IntentFilterprogressfilter=newIntentFilter(Events.UPDATE_DOWNLOADING_PROGRESS);
    registerReceiver(broadcastReceiver,progressfilter);

For sending more data, you can modify method sendBroadcastMessage();. Remember: you must register broadcasts in onResume() & unregister in onStop() methods!

UPDATE

Please don't use my type of communication between Activity & Service. This is the wrong way. For a better experience please use special libs, such us:

1) EventBus from greenrobot

2) Otto from Square Inc

P.S. I'm only using EventBus from greenrobot in my projects,

Solution 3:

Note: You don't need to check if your service is running, CheckIfServiceIsRunning(), because bindService() will start it if it isn't running.

Also: if you rotate the phone you don't want it to bindService() again, because onCreate() will be called again. Be sure to define onConfigurationChanged() to prevent this.

Solution 4:

Messagemsg= Message.obtain(null, 2, 0, 0);
                    Bundlebundle=newBundle();
                    bundle.putString("url", url);
                    bundle.putString("names", names);
                    bundle.putString("captions",captions); 
                    msg.setData(bundle);

So you send it to the service. Afterward receive.

Solution 5:

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.

Post a Comment for "Example: Communication Between Activity And Service Using Messaging"