Launching a service from BroadcastReceiver

My application has Service and BroadcastReceiver , but how do I start a service directly from BroadcastReceiver ? Via

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

doesn't work in BroadcastReceiver , any ideas?

EDIT:

context.startService (..);

works, I forgot the context part

+61
android broadcastreceiver
Jan 09 2018-11-11T00:
source share
6 answers

Do not forget

context.startService(..);

+97
Jan 14 2018-11-11T00:
source share

should be like this:

 Intent i = new Intent(context, YourServiceName.class); context.startService(i); 

be sure to add the service in manifest.xml

+55
Dec 15
source share

use the context the onReceive method of your BroadcastReceiver to start the service component.

 @Override public void onReceive(Context context, Intent intent) { Intent serviceIntent = new Intent(context, YourService.class); context.startService(serviceIntent); } 
+8
Jun 30 '17 at 9:12
source share

Best practice:

When creating an intent, especially since BroadcastReceiver , do not use this as a context. Take context.getApplicationContext() as below

  Intent intent = new Intent(context.getApplicationContext(), classNAME); context.getApplicationContext().startService(intent); 
+5
May 22 '17 at 11:21
source share

Since the onReceive (Context, Intent) receiver method runs in the main thread, it must execute and return quickly. If you need to do a lot of work, be careful with spawning threads or starting background services, because the system can end the whole process after returning onReceive (). For more information, see Effect on Process Status. For long-term work, we recommend:

Call goAsync () in the onReceive () method of your receiver and pass BroadcastReceiver.PendingResult to the background thread. This keeps the translation active after returning from onReceive (). However, even with this approach, the system expects you to finish broadcasting very quickly (up to 10 seconds). This allows you to transfer work to another thread to avoid main thread failures. Planning for JobScheduler developer.android.com

0
Aug 12 '18 at 8:21
source share
  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(); } 
0
Apr 12 '19 at 4:43
source share



All Articles