如何在PendingIntent中发送有序广播?

时间:2012-06-14 02:46:46

标签: android android-pendingintent

我想在PendingIntent中发送有序广播。但我只发现PendingIntent.getBroadcast(this, 0, intent, 0),我认为只能发送常规广播。那么,我该怎么办?

1 个答案:

答案 0 :(得分:4)

我是从http://justanapplication.wordpress.com/tag/pendingintent-getbroadcast得到的:

  

如果onFinished参数不为null,则执行有序广播。

所以你可能想尝试使用onFinished参数集调用PendingIntent.send

然而,我遇到了我必须从通知发送OrderedBroadcast的问题。 我通过创建一个BroadcastReceiver来实现它,它只是将Intent转发为OrderedBroadcast。我真的不知道这是否是一个很好的解决方案。

所以我开始创建一个Intent,其中包含要转发的动作的名称:

// 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.

在我的情况下,我将PendingIntent传递给了通知:

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);

然后我在我的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>

然后OrderedBroadcastForwarder看起来如下:

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);
    }
}