Way to share data with service in android

I have an application where user will choose whether he wants Vibrate or Silent mode. And from the Main Activity I am passing the data as part of Intent to the service (the service is always running).

In the onStartCommand method of service, I get the data for first time and everything works fine. But when I exit the application, after some time may be the service's onStartCommand method is again invoked with no data in the Intent (may be Launcher or android OS is doing it).

Since I am setting a local String variable with data from Intent, I get Null Exception when the onStartCommand method is invoked by OS.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if(mode == null) {
        mode = (String) intent.getExtras().get("mode");
    }
    return super.onStartCommand(intent, flags, startId);
}

Now my problem is how to get the data from activity for the first time and then refer to it in various member methods of service class.

I have tried making the mode variable as static but same issue. Looks as if OS will unload service class at its discretion and then load it back and invoke onStartCommand with plain Intent.

Upvotes: 0

Views: 67

Answers (1)

amatellanes
amatellanes

Reputation: 3735

You must use a SharedPreference to save the state of the variable Vibrate or Silent mode. Here a possible solution:

    SharedPreferences preferences = getApplicationContext()
            .getSharedPreferences("preferences_name", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("mode", "silent"); // Silent Mode
    // editor.putString("mode", "vibrate"); //Vibrate Mode
    editor.commit();

Upvotes: 1

Related Questions