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

use*_*175 7 android android-pendingintent

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

sro*_*oes 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.
Run Code Online (Sandbox Code Playgroud)

就我而言,我将 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);
Run Code Online (Sandbox Code Playgroud)

然后我在清单中定义了以下接收者:

<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>
Run Code Online (Sandbox Code Playgroud)

那么 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);
    }
}
Run Code Online (Sandbox Code Playgroud)