Android 8.0以上無(wú)法收到靜態(tài)廣播消息

1.問(wèn)題描述:在8.0以上系統(tǒng)注冊(cè)靜態(tài)廣播后發(fā)現(xiàn)接收不到廣播,onRecive()得不到執(zhí)行。

2.原因:Android8.0對(duì)靜態(tài)廣播做了限制,在開(kāi)發(fā)文檔中有如下內(nèi)容:

Note: If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for implicit broadcasts (broadcasts that do not target your app specifically), except for a few implicit broadcasts that are exempted from that restriction.
如果您的應(yīng)用程序針對(duì)26級(jí)或更高級(jí)別的API,則無(wú)法使用清單聲明隱式廣播的接收者(不針對(duì)本地廣播),除了幾個(gè)免除該限制的隱式廣播。

詳情可以查看鏈接, Android Developers

3.解決辦法:
1)在廣播的intent中加上Component

Intent intent = new Intent();
intent.setAction("com.example.taoran.CHAIN");
//加上Component
intent.setComponent(new ComponentName(this, FirstReceiver.class));
sendBroadcast(intent, null);

2)若要發(fā)送有序廣播
可以給Intent加上一個(gè)flag

Intent intent = new Intent();
intent.setAction("com.example.taoran.CHAIN");
//設(shè)置一個(gè)flag
intent.addFlags(0x01000000);
sendOrderedBroadcast(intent, null);

為什么要加上這個(gè)flag呢?原因見(jiàn)鏈接: 在A(yíng)ndroid8.0上突破隱式廣播的限制

3)按照Android官方的說(shuō)法,最好還是使用動(dòng)態(tài)廣播,發(fā)送有序廣播可以采用如下方法:

//注冊(cè)動(dòng)態(tài)廣播
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.taoran.CHAIN");
registerReceiver(firstReceiver,filter);
registerReceiver(secondReceiver, filter);
registerReceiver(thirdReceiver, filter);
//發(fā)送有序廣播
Intent intent = new Intent();
intent.setAction("com.example.taoran.CHAIN");
intent.putExtra("limit", limit);
intent.putExtra("msg", "Massage order broadcast");
sendOrderedBroadcast(intent, null);
//記得在onDestroy時(shí)unregister
//...
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容