Login     Sign Up
Cyril Sermon (@admin)
9 months ago

To start a Service, call startService; you can either implicitly specify a Service to start using an action against which the Service is registered, or you can explicitly specify the Service using its class.

If the Service requires permissions that your application does not have, this call will throw a

SecurityException. The snippet below demonstrates both techniques available for starting a Service:

Implicitly start a Service startService(new Intent(MyService.MY_ACTION));

Explicitly start a Service

startService(new Intent(this, MyService.class));

To use this example, you would need to include a MY_ACTION property in the MyService class and use an Intent Filter to register it as a provider of MY_ACTION.

To stop a Service, use stopService, passing an Intent that defines the Service to stop. This next code snippet first starts and then stops a Service both explicitly and by using the component name returned when calling startService:

ComponentName service = startService(new Intent(this, BaseballWatch.class));

Stop a service using the service name. stopService(new Intent(this, service.getClass()));

Stop a service explicitly. try {

Class serviceClass = Class.forName(service.getClassName()); stopService(new Intent(this, serviceClass));

} catch (ClassNotFoundException e) {}

If startService is called on a Service that’s already running, the Service’s onStart method will be executed again. Calls to startService do not nest, so a single call to stopService will terminate it no matter how many times startService has been called.