Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stopService(intent_with_extras) - how do you read those extras from within the service to stop?

I have a Service that can be stopped in multiple ways. Whenever I call stopService(Intent), I pass an intent with some extras. How do you retrieve those extras?

Thanks.

like image 500
ekawas Avatar asked Jan 14 '11 17:01

ekawas


2 Answers

You need to override onStartCommand() in your Service this is how you get a reference to the incoming intent from startService.

In this case you would have a special action in your intent to tell the service to stop itself. You add extras to this intend which can be read in the onStartCommand() method.

Sample Code

public class MyService extends Service {
    @Override
    public int onStartCommand(final Intent intent, final int flags, final int startId) {
         final String yourExtra = intent.getStringExtra(YOUR_EXTRA_ID);
         // now you can e.g. call the stopSelf() method but have the extra information
    }
}

Explanation

Every time you call context.startService(Intent) onStartCommand() will be called. If the service is already running a new service isn't created but onStartCommand is still called. This is how you can get a new intent with extras to a running service.

like image 75
Nathan Schwermann Avatar answered Nov 15 '22 05:11

Nathan Schwermann


I found that the extras are not passed with the intent when stopService is called. As a workaround, simply call startService(Intent) and stopService(Intent) right after one another.

Example code from Activity:

Intent j = new Intent(SocketToYa.this, AccelerometerDataSocket.class); j.putExtra("com.christophergrabowski.sockettoya.DestroyService", true); startService(j); stopService(j);

In Service.onStartCommand,

intent.hasExtra("com.christophergrabowski.sockettoya.DestroyService")

will evaluate to true, and you will destroy your service the way intended by the API (i.e., by calling stopService, which will in turn call OnDestroy after onStartCommand is called).

like image 30
Christopher Grabowski Avatar answered Nov 15 '22 04:11

Christopher Grabowski