【发布时间】:2021-05-05 09:35:16
【问题描述】:
我知道待定意图的概念,但标志令人困惑。
即使是 android 文档也很难理解
有人可以通过示例提供对未决意图标志的解释,特别是 FLAG_ONE_SHOT 和 FLAG_NO_CREATE?
【问题讨论】:
-
这个答案没有帮助。我只想要每个标志的示例和解释
标签: android android-pendingintent
我知道待定意图的概念,但标志令人困惑。
即使是 android 文档也很难理解
有人可以通过示例提供对未决意图标志的解释,特别是 FLAG_ONE_SHOT 和 FLAG_NO_CREATE?
【问题讨论】:
标签: android android-pendingintent
PendingIntents 由 Android 框架管理。当您调用PendingIntent.getXXX() 方法之一时,框架会尝试查找与您传递给getXXX() 方法的参数匹配的现有PendingIntent。如果它找到匹配的PendingIntent,它只会将其返回给调用者。如果它没有找到匹配的PendingIntent,它将(通常)创建一个新的PendingIntent 并将其返回给调用者。您可以使用以下标志更改此标准行为:
FLAG_NO_CREATE 用于获取现有的PendingIntent。如果存在匹配的PendingIntent,则将其返回给调用者。如果不存在匹配的PendingIntent,则不会发生任何事情。框架不会创建新的PendingIntent,并且该方法将null 返回给调用者。您可以使用此方法来确定特定的PendingIntent 是否存在。您也可以使用此方法获取现有的PendingIntent,以便取消它。
FLAG_ONE_SHOT 很奇怪。根据文档,此标志应导致PendingIntent 在使用(发送)后被删除。但是,此标志还有其他副作用。例如,如果您使用此标志创建一个PendingIntent,然后尝试通过使用FLAG_NO_CREATE 调用PendingIntent.getXXX() 来获取此PendingIntent(或测试它是否存在),则框架将始终返回null。出于这个原因,我从不使用它,我也建议永远不要使用它。
FLAG_CANCEL_CURRENT 用于删除现有的PendingIntent 并创建一个新的。框架首先尝试找到匹配的PendingIntent。如果找到,它会取消(删除)这个PendingIntent。这意味着任何持有此PendingIntent 的应用程序将无法触发(发送)它。然后框架使用提供的参数创建一个新的PendingIntent,并将其返回给调用者。
FLAG_UPDATE_CURRENT 用于更新现有的PendingIntent。框架首先尝试找到匹配的PendingIntent。如果找到一个,现有PendingIntent 中的“附加”将被提供的Intent 参数中的“附加”覆盖。如果没有找到匹配的PendingIntent,则使用提供的参数创建一个新的。找到的(或新创建的)PendingIntent 返回给调用者。
注意:有关 Android 框架如何尝试查找“匹配”PendingIntent:https://stackoverflow.com/a/29590084/769265
【讨论】:
PendingIntents 不要“跑”。他们被发送。根据PendingIntent 包裹的Intent,这可能导致启动Activity、BroadcastReceiver 或Service。请解释您的要求。
When you call one of the PendingIntent.getXXX() methods, the framework tries to find an existing PendingIntent that matches the parameters you pass to the getXXX() method,你说的是it tries to find an existing intent。我的疑问是未决意图是否会在后台运行?这句话到底是什么意思?