Android高版本收不到靜態注冊的廣播


Beginning with Android 8.0 (API level 26), the system imposes additional restrictions on manifest-declared receivers.
If your app targets Android 8.0 or higher, you cannot use the manifest to declare a receiver for most implicit broadcasts (broadcasts that don't target your app specifically). You can still use a context-registered receiver when the user is actively using your app.

Android為了防止靜態注冊的廣播耗費資源,禁用了一些在Manifest文件中注冊的廣播。導致收不到消息,在logcat中能看到類似這樣的日志

2019-10-08 00:02:29.523 350-365/system_process W/BroadcastQueue: Background execution not allowed: receiving Intent { act=android.intent.action.BATTERY_LOW flg=0x4000010 (has extras) } to com.hncj.android/.PowerStateReceiver

說明廣播被系統攔截了.

這里是仍然可以使用靜態注冊的系統廣播:
https://developer.android.google.cn/guide/components/broadcast-exceptions?hl=en

解決方法:
1、想要接收系統廣播,似乎只有降低targetSdkVersion為25或以下,但此種方式Manifest文件會報錯,需要在前面加一句:
//noinspection ExpiredTargetSdkVersion
targetSdkVersion 25

降低targetSdkVersion后,項目也會編譯報錯,找不到一些類,資源、樣式等文件。需要刪除build.gradle中的:

implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

同時activity類不要繼承AppCompatActivity,直接繼承Activity.酌情刪除或修改Manifest.xml中的theme、roundIcon等樣式,酌情刪除一些圖片,變量定義文件。

2、對於自定義的廣播,想要使用靜態注冊,網上也提供了解決方案:

如:在sendBroadcast方法之前,調用intent的setPackage或setComponent方法,為其設置具體的接收者;

或者使用intent的addFlag方法,阻止系統攔截廣播

intent.addFlags(0x01000000);

詳細可參考: https://www.jianshu.com/p/5283ebc225d5?utm_source=oschina-app


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM