Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data to onDestroy() of Service

I want to know if the service was terminated from a particular activity, so I'm passing a string from that activity while calling stopServivce(service).

Here's the code :

Intent service = new Intent(Activity.this,
                        service.class);
                service.putExtra("terminate", "activity terminated service");
                stopService(service);

But I can seem to access this variable with getIntent().getExtras().getString("terminate); in the onDestroy() method.

[EDIT]

I found a way around this obstacle, but I'd like my question to still be answered. I just did whatever I had to do in the onDestroy() method in the activity and then called stopService(service). I was lucky that my situation didn't need anything more complicated.

like image 568
Karthik Balakrishnan Avatar asked Jan 16 '13 06:01

Karthik Balakrishnan


People also ask

What is onDestroy () meant for?

onDestroy()the system is temporarily destroying the activity due to a configuration change (such as device rotation or multi-window mode)

Does stopSelf call onDestroy?

You should call stopSelf () to stop a service. After you call it, the Android Framework will call onDestroy() method automatically.

What happens when onDestroy is called?

If onDestroy() is called as the result of a configuration change, the system immediately creates a new activity instance and then calls onCreate( ) on that new instance in the new configuration.

What is used to send back data to the activity?

This provides a pipeline for sending data back to the main Activity using setResult . The setResult method takes an int result value and an Intent that is passed back to the calling Activity. Intent resultIntent = new Intent(); // TODO Add extras or a data URI to this intent as appropriate. resultIntent.


1 Answers

There is no way of accessing the Intent in onDestroy. You have to signal the service some other way (Binder, Shared Preferences, Local Broadcast, global data, or Messenger). A nice example of using broadcast is given in this answer. You can also get this to work by calling startService instead of stopService. startService only starts a new services if one does not already exist, so multiple calls to startService is mechanism yo send Intents to the service. You see this trick is use by BroadcastReceivers. Since you have access to the Intent in onStartCommand, so you can implement termination by check the Intent extras and calling stopSelf if instructed to terminate. Here is a sketch of it in action --

public int onStartCommand(Intent intent, int flags, int startId) {
        final String terminate = intent.getStringExtra("terminate");

        if(terminate != null) {
            // ... do shutdown stuff
            stopSelf();
        }
        return START_STICKY;
    }
like image 191
iagreen Avatar answered Nov 15 '22 09:11

iagreen