【问题标题】:How to send an ordered broadcast in a PendingIntent?如何在 PendingIntent 中发送有序广播?
【发布时间】:2012-06-14 02:46:45
【问题描述】:

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

【问题讨论】:

    标签: android android-pendingintent


    【解决方案1】:

    我从http://justanapplication.wordpress.com/tag/pendingintent-getbroadcast 得到这个:

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

    因此,您可能想尝试使用 onFinished 参数集调用 PendingIntent.send

    但是,我遇到了必须从通知发送 OrderedBroadcast 的问题。 我通过创建一个将 Intent 作为 OrderedBroadcast 转发的 BroadcastReceiver 使其工作。我真的不知道这是否是一个好的解决方案。

    所以我首先创建了一个 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-08
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-21
      相关资源
      最近更新 更多