How to receive action by BroadcastReceiver inside Service

0

I have problem with receiving an intent sended by widget as PendingIntent:

intent = new Intent(MyService.MY_ACTION);
pendingIntent = PendingIntent.getService(this, 0, intent, 0);
views.setOnClickPendingIntent(R.id.button, pendingIntent);

I added a broadcast receiver to MyService:

private BroadcastReceiver mIntentReceiver = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        Log.d(TAG, "Intent command received");
        String action = intent.getAction();

        if( MY_ACTION.equals(action))
        {
            doSomeAction();
        }
    }
};

and finally I registered this receiver i onCreate method of the service:

IntentFilter filter = new IntentFilter();
filter.addAction(MY_ACTION);
registerReceiver(mIntentReceiver, filter);

And now when th MyService is running and I click the button, I get :

09-21 14:21:18.723: WARN/ActivityManager(59): Unable to start service Intent { act=com.myapp.MyService.MY_ACTION flg=0x10000000 bnds=[31,280][71,317] }: not found

I also tried to add an intent-filter (with MY_ACTION action) to manifest file to MyService but it causes calling onStartCommand method of MyService. And that is not what I want. I need to call the onReceive method of mIntentReceiver.

android
service
action
broadcastreceiver
android-pendingintent
asked on Stack Overflow Sep 21, 2011 by Bhiefer • edited Jun 28, 2019 by Cœur

2 Answers

3

What do you want to do?

If you register a broadcast receiver in your Service onCreate method then:

  • You should raise a broadcast intent, not a service intent. Change this:

    pendingIntent = PendingIntent.getService(this, 0, intent, 0);

To this:

pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
  • You service should be running to listen for this broadcast event, this will not run your service, since you are registering the receiver when the service is created.
answered on Stack Overflow Sep 21, 2011 by aromero
1

For such purposes you should extend your service from IntentService. You will receive the broadcast in onHandleIntent() method of your service.

answered on Stack Overflow Sep 21, 2011 by Ronnie

User contributions licensed under CC BY-SA 3.0