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.
onDestroy()the system is temporarily destroying the activity due to a configuration change (such as device rotation or multi-window mode)
You should call stopSelf () to stop a service. After you call it, the Android Framework will call onDestroy() method automatically.
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.
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.
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 Intent
s 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;
}
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