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

4

3

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

Tunicle answered 10/1, 2011 at 22:1 Comment(0)
H
7

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.

Hunter answered 10/1, 2011 at 23:6 Comment(1)
Awesome approach with the local broadcasts, between, you know if we can bind to running services? (for 2way communication)Saddlebow
C
1

I don't think relying on onDestroy() is a good thing. There are couple of approaches you can take.

  1. suggest to bind the service so that you could write your userstop notification in onUnbind http://developer.android.com/guide/topics/fundamentals.html#servlife

  2. Other option (not sure if this works) is to post your variable to SharedPreferences and obtain it from onDestroy(). [You need to check if this works in debug mode or LogCat messages.

Candelaria answered 10/1, 2011 at 22:31 Comment(0)
G
-1

I have the same setup in my app using CheckBoxPreference in my activity and getSharedPreference in service class's onCreate. Checking the checkbox starts the service. Unchecking stops the service.

Listen and handle preference click in my Activity:

    getPreferenceManager().findPreference("prefEnable").setOnPreferenceClickListener(new OnPreferenceClickListener()
    {
        // not used: Intent intent = new Intent(this, MyService.class);
        @Override
        public boolean onPreferenceClick(Preference preference) {
            CheckBoxPreference cb = (CheckBoxPreference) preference;
            if (cb.isChecked()) {
                Log.d(TAG, "User enabled service");
                // code to start service
            } else {
                Log.d(TAG, "User disabled service");
                // code to stop service
            }
            return true;
        }
    });

Get my "prefEnable" preference within my service onCreate:

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    Boolean isEnabled = preferences.getBoolean("prefEnable", false);

Perhaps in your onDestroy, you can re-purpose this and say:

if (isEnabled==false) {
   *** notification code ***
Gulosity answered 11/1, 2011 at 22:5 Comment(1)
And this working example was downvoted 3 years after I posted, why?Gulosity
M
-1

// You can pass the parameter in this simple way:-

Intent serviceIntent = new Intent(this,ListenLocationService.class); 
   serviceIntent.putExtra("From", "Main");
   startService(serviceIntent);
//and get the parameter in onStart method of your service class

    @Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
     Bundle extras = intent.getExtras(); 
if(extras == null)
    Log.d("Service","null");
else
{
    Log.d("Service","not null");
    String from = (String) extras.get("From");
    if(from.equalsIgnoreCase("Main"))
        StartListenLocation();
}

}
Enjoy :)
Maccabees answered 28/5, 2013 at 12:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.