在Android 8之前,如果要發送自定義的靜態廣播,做好其他配置后,只需實例化一個Intent對象intent,然后將其作為參數傳入sendBroadcast()方法中即可,例如
Intent intent = new Intent(action);
intent.putExtra(INTENT_DATA_PUSH, data);
intent.addCategory(context.getPackageName());
context.sendBroadcast(intent);
但在Android 8之后需要setComponent才能收到廣播消息,其中,ComponentName接收兩個參數,參數1是自定義廣播的包名,參數2是自定義廣播的路徑。
Intent intent = new Intent(action);
intent.putExtra(INTENT_DATA_PUSH, data);
intent.addCategory(context.getPackageName());
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
intent.setComponent(new ComponentName(context.getPackageName(), com.test.broadcastReceiver);
}
context.sendBroadcast(intent);
因為在Android 8.0 及以上 在xml中注冊的廣播,在接收的時候收到了額外的限制,如果你的app目標等級是26及以上,將無法接收到xml注冊的廣播,這是google 為了app注冊的靜態廣播導致耗電加的限制,具體請查看【https://developer.android.com/guide/components/broadcasts.html】