2

In my Android app I have a service which should be restarted automatically after it gets killed. I found out that this can be done using START_STICKY.

But apparently when the service is automatically restarted, the intent is null. The problem however, is that the intent is used to pass along a value. See the example below:

public class MyService extends Service {
    public static final String MY_STRING_HANDLE = "MyString";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        // Read my string from intent
        Bundle extras = intent.getExtras(); // ERROR: Intent can be null
        if (extras == null) {
            throw new Error("Intent did not contain my string");
        }

        String myString = extras.getString(MY_STRING_HANDLE);
        if (myString == null || myString.isEmpty()) {
            throw new Error("Intent did not contain my string");
        }

        // Do something with my string
        doSomeThing(myString);

        return START_STICKY;
    }
}

So usually I start the service like this:

Intent intent = new Intent(activity, MyService.class);
intent.putExtra(MyService.MY_STRING_HANDLE, "Example string");
activity.startService(intent);

This works, but when the service is killed and automatically restarted I get the following result:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference

So my question is: If I cannot use intents, then how should I pass on values (i.e. myString) to my service?


Regarding possible duplicate: My question is not about why the intent is null, it's about how I can handle this.

Duncan Lukkenaer
  • 12,050
  • 13
  • 64
  • 97
  • Possible duplicate of [Reasons that the passed Intent would be NULL in onStartCommand](https://stackoverflow.com/questions/8421430/reasons-that-the-passed-intent-would-be-null-in-onstartcommand) – ADM Dec 19 '18 at 15:11
  • @ADM Please see the note below my question. – Duncan Lukkenaer Dec 19 '18 at 15:14
  • Yeah now you put it . Well you already have the answer below and in above link also. yet again By CommonsWare... – ADM Dec 19 '18 at 15:16

1 Answers1

4

Use START_REDELIVER_INTENT instead of START_STICKY. Also, make sure that for each Intent that you completely process, call stopSelf() with the ID value supplied in the corresponding call to onStartCommand().

Then, if Android terminates your process (e.g., low memory), Android will restart your service and deliver to you any Intent objects that you did not indicate (via stopSelf()) that you processed.


Alternatively, do not rely on Intent extras. Instead, store your data in a file, database, SharedPreferences, server, etc., and have your service fetch the data from there.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491