Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting Service from BroadcastReceiver

I have a Service and BroadcastReceiver in my application, 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

like image 388
Samuel Avatar asked Jan 09 '11 20:01

Samuel


People also ask

Can we start a service from BroadcastReceiver?

Demonstrates how to run an Android service in a separate process using a separate . so lib file, and how to communicate with Qt using a BroadcastReceiver. This example demonstrates how to create and run an Android service in a separate process that uses a separate .

How do I send data from BroadcastReceiver to service?

In receiver, you can just put all params into a Bundle, and use startService(Intent) containing that bundle to call the target service. In service, you parse the bundle and get all params. This is a solution and it's works fine.

When would you use a BroadcastReceiver?

Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.

Is it necessary to unregister BroadcastReceiver?

It's always suggested to register and unregister broadcast receiver programmatically as it saves system resources.


2 Answers

Don't forget

context.startService(..);

like image 82
Samuel Avatar answered Oct 09 '22 02:10

Samuel


should be like that:

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

be sure to add the service to manifest.xml

like image 39
Zeev G Avatar answered Oct 09 '22 02:10

Zeev G