gpt4 book ai didi

android - 显式 Intent 广播接收器 - Action 过滤器行为

转载 作者:行者123 更新时间:2023-11-29 23:49:55 25 4
gpt4 key购买 nike

我正在努力使我的应用在 Intent 方面适应新的 Android O 方法,尤其是广播接收器。我怀疑我是否正确理解了对服务/广播接收器施加的新限制。我开始尝试了一下。我的目标是 API 级别 27(最低 API 级别 26),现在我对结果更加困惑。

  1. 创建应用com.example.app

  2. 声明 (AndroidManifest.xml) 广播接收器:

<receiver android:name=".BcastReceiver">
<intent-filter>
<action android:name="com.example.app.WAKE_UP" />
</intent-filter>
</receiver>

让我感到困惑的是通过 adb shell intent 调用的结果:

A)匹配 Action

am broadcast -n "com.example.app/.BcastReceiver" -a "com.example.app.WAKE_UP"

B) Non-matching Action

am broadcast -n "com.example.app/.BcastReceiver" -a "nonsense"

C) Missing Action

am broadcast -n "com.example.app/.BcastReceiver"

Any of these A), B) or C) invocations actually cause that application is instantiated, broadcast receiver is called.

It seems that action action intent filter is actually ignored. Therefore I removed the intent filter in AndroidManifest.xml:

<receiver android:name=".BcastReceiver"/>

但是通过该声明,A)、B) 或 C) 都无法调用广播接收器。似乎 intent 过滤器必须存在,但它的内容被忽略了。有什么提示是为什么吗?

最佳答案

今天找到原因了。它与 android:exported 标志有关。正如 official documentation 中所述:

The default value depends on whether the broadcast receiver contains intent filters. The absence of any filters means that it can be invoked only by Intent objects that specify its exact class name. This implies that the receiver is intended only for application-internal use (since others would not normally know the class name). So in this case, the default value is "false". On the other hand, the presence of at least one filter implies that the broadcast receiver is intended to receive intents broadcast by the system or other applications, so the default value is "true".

如果缺少 intent 过滤器,则不会导出广播接收器,因此无法从应用程序外部调用。如果有intent filter,则默认导出广播接收器。 它同时适用于服务和广播接收器 - 使用 additional limitation后台应用程序的后台服务将不会启动。

然而仍然存在与忽略操作的不一致,但我个人理解,如果 startservice/broadcast 是显式的 - 明确/唯一地命名目标组件 - 没有理由考虑操作 Intent 过滤器。

关于android - 显式 Intent 广播接收器 - Action 过滤器行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50977163/

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