7

我想在 PendingIntent 中发送有序广播。但我只找到了PendingIntent.getBroadcast(this, 0, intent, 0),我认为只能发送常规广播。那么,我能做些什么呢?

4

1 回答 1

4

I got this from http://justanapplication.wordpress.com/tag/pendingintent-getbroadcast:

If the onFinished argument is not null then an ordered broadcast is performed.

So you might want to try calling PendingIntent.send with the onFinished argument set.

However, I ran into the problem that I had to send an OrderedBroadcast from a Notification. I got it working by creating a BroadcastReceiver which just forwards the Intent as an OrderedBroadcast. I really don't know whether this is a good solution.

So I started out by creating an Intent which holds the name of the action to forward to as an extra:

// the name of the action of our OrderedBroadcast forwarder
Intent intent = new Intent("com.youapp.FORWARD_AS_ORDERED_BROADCAST");
// the name of the action to send the OrderedBroadcast to
intent.putExtra(OrderedBroadcastForwarder.ACTION_NAME, "com.youapp.SOME_ACTION");
intent.putExtra("some_extra", "123");
// etc.

In my case I passed the PendingIntent to a Notification:

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
Notification notification = new NotificationCompat.Builder(context)
        .setContentTitle("Notification title")
        .setContentText("Notification content")
        .setSmallIcon(R.drawable.notification_icon)
        .setContentIntent(pendingIntent)
        .build();
NotificationManager notificationManager = (NotificationManager)context
    .getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int)System.nanoTime(), notification);

Then I defined the following receivers in my Manifest:

<receiver
    android:name="com.youapp.OrderedBroadcastForwarder"
    android:exported="false">
    <intent-filter>
        <action android:name="com.youapp.FORWARD_AS_ORDERED_BROADCAST" />
    </intent-filter>
</receiver>
<receiver
    android:name="com.youapp.PushNotificationClickReceiver"
    android:exported="false">
    <intent-filter android:priority="1">
        <action android:name="com.youapp.SOME_ACTION" />
    </intent-filter>
</receiver>

Then the OrderedBroadcastForwarder looks as follows:

public class OrderedBroadcastForwarder extends BroadcastReceiver
{
    public static final String ACTION_NAME = "action";

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Intent forwardIntent = new Intent(intent.getStringExtra(ACTION_NAME));
        forwardIntent.putExtras(intent);
        forwardIntent.removeExtra(ACTION_NAME);

        context.sendOrderedBroadcast(forwardIntent, null);
    }
}
于 2013-05-30T12:30:27.223 回答