1. 问题的前提:
本人维护的一个应用是通过按键发送一个自定义广播,然后拉起服务。原来项目开发是在Android6,但是安装到Android8上面,死活收不到广播。
2.原因:
Android8在静态广播的使用上做了一些限制具体可查看Google:Android 8.0 功能和 API
3. 解决办法:
(1)使用动态广播代替静态广播。
(2)保留原来的静态广播,但是加入Component或者Package参数。
看下方式2的实现:
广播Action定义:
广播接收方应用包名:
广播接收方接收器包名+类名路径:
以上定义需要替换为你实际项目中广播接收方的包名和广播接收器类名。
如下是发送方的代码:
Intent intent = new Intent("");
(new ComponentName("",
""));
sendBroadcast(intent);
或者以下实现方式发送也可以:
Intent intent = new Intent("");
("");
sendBroadcast(intent);
当然你对广播源码有了解的话也可以这样实现:
Intent intent = new Intent("");
(0x01000000);
sendBroadcast(intent);
第三种加的是如下的flag,没被豁免的隐式广播之所以发送不出去,是因为源码中加了这个标志位判断,所以我们加上以后广播发送正常,但是因为该flag是隐藏的,所以需要硬编码使用。(个人不建议这样做)
/**
* If set, the broadcast will always go to manifest receivers in background (cached
* or not running) apps, regardless of whether that would be done by default. By
* default they will only receive broadcasts if the broadcast has specified an
* explicit component or package name.
*
* NOTE: dumpstate uses this flag numerically, so when its value is changed
* the broadcast code there must also be changed to match.
*
* @hide
*/
public static final int FLAG_RECEIVER_INCLUDE_BACKGROUND = 0x01000000;
参考文章:
博客1:Android 8.0 功能和 API
博客2:Android8.0广播使用
博客3:Android8.0后静态注册广播的用法