Starting Service from BroadcastReceiver
I have a Service
and BroadcastReceiver
in my ap开发者_JAVA技巧plication, but how do I launch the service directly from the BroadcastReceiver
? Using
startService(new Intent(this, MyService.class));
does not work in a BroadcastReceiver
, any ideas?
EDIT:
context.startService(..);
works, I forgot the context part
Don't forget
context.startService(..);
should be like that:
Intent i = new Intent(context, YourServiceName.class);
context.startService(i);
be sure to add the service to manifest.xml
use the context
from the onReceive
method of your BroadcastReceiver to start your service component.
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, YourService.class);
context.startService(serviceIntent);
}
Best Practice :
While creating an intent especially while starting from BroadcastReceiver
, dont take this as context.
Take context.getApplicationContext()
like below
Intent intent = new Intent(context.getApplicationContext(), classNAME);
context.getApplicationContext().startService(intent);
try {
Intent intentService = new Intent(context, MyNewIntentService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intentService );
} else {
context.startService(intentService );
}
} catch (Exception e) {
e.printStackTrace();
}
It's better to use ContextCompat:
Intent serviceIntent = new Intent(context, ForegroundService.class);
ContextCompat.startForegroundService(context, serviceIntent);
Because a receiver's onReceive(Context, Intent) method runs on the main thread, it should execute and return quickly. If you need to perform long running work, be careful about spawning threads or starting background services because the system can kill the entire process after onReceive() returns. For more information, see Effect on process state To perform long running work, we recommend:
Calling goAsync() in your receiver's onReceive() method and passing the BroadcastReceiver.PendingResult to a background thread. This keeps the broadcast active after returning from onReceive(). However, even with this approach the system expects you to finish with the broadcast very quickly (under 10 seconds). It does allow you to move work to another thread to avoid glitching the main thread. Scheduling a job with the JobScheduler developer.android.com
精彩评论