【问题标题】:How to send Order broadcast receiver using pending intent android如何使用待定意图android发送订单广播接收器
【发布时间】:2015-12-21 08:28:51
【问题描述】:

嗨,我有这样的功能,当用户点击通知时,我必须检查我的应用程序是否在前台,如果是这样,只需关闭通知。否则需要打开应用程序。

我使用有序广播的概念来实现,但我坚持从待定意图调用有序广播接收器。

【问题讨论】:

  • 您只能从代码发送有序广播。您不能创建将发送有序广播的PendingIntent。为什么你需要一个有序的广播来解决你的问题?请解释一下。

标签: android broadcastreceiver android-notifications android-pendingintent android-broadcastreceiver


【解决方案1】:

要使用PendingIntent 发送有序广播,请使用send() 方法之一,例如this one,它采用PendingIntent.OnFinished 参数。此功能没有明确记录,只有PendingIntent.OnFinished 的参数描述给出了一些支持有序广播的提示。

这是发送有序广播的示例:

Intent i = new Intent("com.my.package.TEST_ACTION");

PendingIntent.OnFinished listener = new PendingIntent.OnFinished() {
    @Override
    public void onSendFinished(PendingIntent pendingIntent, Intent intent,
                               int resultCode, String resultData, Bundle resultExtras) {
        Log.i("TEST", String.format("onSendFinished(): result=%d action=%s",
                            resultCode, intent.getAction()));
    }
};

PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);

int initResult = -1;

try {
    pi.send(initResult, listener, null);
} catch (PendingIntent.CanceledException e) {
    e.printStackTrace();
}

我确认这会产生一个有序广播,方法是定义一些具有这种通用形式的接收器,并在清单中以不同的优先级注册:

public class ReceiverA extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("AAAA", String.format("result=%d ordered=%b", getResultCode(), isOrderedBroadcast()));
        setResultCode(1111);
    }
}

logcat 输出确认接收器按预期顺序调用,isOrderedBroadcast() 对每个都为真,setResultCode() 设置的结果代码被传递给下一个接收器,最后传递给@987654331 @回调。

【讨论】:

  • @David Wasser:因为这个答案与你对这个问题的评论不一致,而且你使用 Android 的历史比我长,我非常感谢你对此的评论和 cmet。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 2010-12-07
相关资源
最近更新 更多