gpt4 book ai didi

android - Intent 的标志和 PendingIntent.getBroadcast

转载 作者:行者123 更新时间:2023-11-29 16:17:17 24 4
gpt4 key购买 nike

我的代码中出现了这个异常:

...IllegalArgumentException...Cant use FLAG_RECEIVER_BOOT_UPGRADE here...

查看 android 源代码似乎无法将标志设置为将通过以下方式触发的 Intent:

PendingIntent.getBroadcast(...);

这里是安卓源代码:

...
if (type == INTENT_SENDER_BROADCAST) {
if ((intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
throw new IllegalArgumentException("Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
}
}
...

这是我的代码:

Intent myIntent = new Intent(context, MyReceiver.class);
//myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if i remove the comment it doesn't work
PendingIntent pending = PendingIntent.
getBroadcast(context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

我不清楚原因,请问谁能帮我解释一下?

最佳答案

当您使用 getBroadcast() 获得 PendingIntent 时,此 Intent 将被广播到 BroadcastReceivers。它不会用于启动 Activity 。所以你不能设置任何与 Activity 相关的标志。无论如何,它们在这种情况下没有任何意义。

为什么要在要广播的 Intent 中设置 FLAG_ACTIVITY_NEW_TASK?这没有意义。

Android 将 Intent 用于 3 个完全不同的目的:

  1. 启动/与 Activity 通信
  2. 启动/与服务通信
  3. 广播到 BroadcastReceiver

PendingIntent 类提供了 3 种不同的方法来为每个不同的目的获取 PendingIntent:

  1. getActivity()
  2. getService()
  3. getBroadcast()

您需要确保为正确的目的使用正确的方法。

是的,您可以在 PendingIntent 中设置与 Activity 相关的 Intent 标志,只要您调用 getActivity() 获取 PendingIntent。

关于android - Intent 的标志和 PendingIntent.getBroadcast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8584107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com