Android8.0后静态注册广播的用法

Android O对隐式广播进行了限制,我们想要正常使用静态注册的广播,有两种推荐做法:

方式一:发送显式广播

这种广播发送形式,需要我们指定需要接收广播的应用的包名和广播接收器类名,也就是一对一发送,严格说叫单播。

Intent intent = new Intent(actionName);
intent.setComponent(new ComponentName(packageName, className));
intent.putExtra(key, value);
sendBroadcast(intent);

方式二:addFlag

我们查阅Android广播源码发现,没被豁免的隐式广播之所以发送不出去,是因为加了标志位判断:

/**
 * 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;

有这个标志位的广播,都是被放行的,那我们可以在发送广播的时候,添加这个标志位。不过,这个变量是隐藏的API,如果是普通应用,我们想要使用,直接硬编码即可:

intent.addFlags(0x01000000);

附注

  1. android.intent.action.BOOT_COMPLETED 开机广播属于后台有序广播;
  2. 广播ANR超时时间:前台广播10s,后台广播60s
    // How long we allow a receiver to run before giving up on it.  
    static final int BROADCAST_FG_TIMEOUT = 10*1000;  
    static final int BROADCAST_BG_TIMEOUT = 60*1000;  
    

你可能感兴趣的:(Android,进阶)