Search code examples
androidparametersserviceandroid-activityondestroy

How to pass a parameter from an activity to a service...when the user stop the service


I have an activity with a checkbox: if the chekbox is unchecked then stop the service. this is a snippet of my activity code:

    Intent serviceIntent = new Intent();
    serviceIntent.setAction("com.android.savebattery.SaveBatteryService");

    if (*unchecked*){
        serviceIntent.putExtra("user_stop", true);
        stopService(serviceIntent);

when I stop the service I pass a parameter "user_stop" to say at the service that has been a user to stop it and not the system (for low memory).

now I have to read the variable "user_stop" in void onDestroy of my service:

public void onDestroy() {
super.onDestroy();

Intent recievedIntent = getIntent(); 
boolean userStop= recievedIntent.getBooleanExtra("user_stop");

    if (userStop) {
       *** notification code ****

but it doesn't work! I can't use getIntent() in onDestroy!

any suggestion?

thanks

Simone


Solution

  • I see two ways of doing this:

    1. Using Shared Preferences.
    2. Using local broadcasts.

    The first approach is an easy and straightforward way. But it is not very flexible. Basically you do:

    • a. Set "user stop" shared preference to true.
    • b. Stop service
    • c. In you service in onDestroy check what is the value of "user stop" preference.

    The other approach is a better way but requires more code.

    • a. Define a string constant in you service class:
    final public static string USER_STOP_SERVICE_REQUEST = "USER_STOP_SERVICE".
    • b. Create an inner class BroadcastReceiver class:

      public class UserStopServiceReceiver extends BroadcastReceiver  
      {  
          @Override  
          public void onReceive(Context context, Intent intent)  
          {  
              //code that handles user specific way of stopping service   
          }  
      }
      
    • c. Register this receiver in onCreate or onStart method:

      registerReceiver(new UserStopServiceReceiver(),  newIntentFilter(USER_STOP_SERVICE_REQUEST));
    • d. From any place you want to stop your service:

      context.sendBroadcast(new Intent(USER_STOP_SERVICE_REQUEST));

    Note that you can pass any custom arguments through Intent using this approach.