简体   繁体   中英

Sending a BroadcastReceiver intent to a service

Typically you start a service like this

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

but what I want to do is send an intent that was received in a BroadcastReceiver to a service. If I start a service the way shown above that wont get the intent from the BroadcastReceiver correct?

Basically I just want my BroadcastReceiver to start my service and then let the service itself handle what kind of intent was received

is this possible?

Send Intent from BroadcastReceiver to Service as:

Intent intent = new Intent(context,MessageService.class);
String value = "String you want to pass";
String name = "data";
intent.putExtra(name, value);
context.startService(intent);

Reciver Intent in onStartCommand method of service:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    if (intent.getStringExtra("data") != null) {
     {
       String str=intent.getStringExtra("data");//get data here sended from BroadcastReceiver 
     }

    return super.onStartCommand(intent,flags,startId);
}

for how we communicate between Service and BroadcastReceiver see this post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM