views:

155

answers:

1

I have a BroadcastReceiver that works fine, i.e. executing this code from an Activity, the receiver receives the intent:

Intent toggleIntent = new Intent(this, ToggleServicesReceiver.class);
this.sendBroadcast(toggleIntent);

But I am trying to do the same from a button in a Widget:

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {  
    ...
    Intent toggleIntent = new Intent(context, ToggleServicesReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, toggleIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    remoteView.setOnClickPendingIntent(R.id.widget_button, pendingIntent);
}

The code is called (I've checked it with the debugger), but when the user clicks the button, the same BroadcastReceiver does not receive the Intent.

What could be happening?

Edit: The BroadcastReceiver is defined in AndroidManifest.xml, and now I'm not sure if the <intent-filter> is needed:

<receiver android:name="foo.receivers.ToggleServicesReceiver">
    <intent-filter>
        <action android:name="foo.intent.action.SERVICES_TOGGLE" />
    </intent-filter>
</receiver>

Edit: I've also found this in a forum, it could be related with this problem

You simply can not do this. A BroadcastReceiver component only "lives" for the duration of the call to onReceiveIntent(); it is not allowed to use registerReceiver in it, because by the time you return from that method (at which point you could first receive anything from your register), the component is no longer alive, and the system could kill at any time to reclaim memory.

A: 

Consider this:

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, toggleIntent, PendingIntent.FLAG_ONE_SHOT);
Paul Turchenko