Starting Service from BroadcastReceiver
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();
}