我碰到這個問題的時候去搜,找到的是因爲安卓版本過高,系統比較嚴格,因此發送廣播的時候需要多點步驟,但是在看書的過程中,又發現好像這個還分動態註冊和靜態註冊。其實差別只是多一行少一行的事,下面分別說說,PS.我的avd是Android 28。
靜態註冊
如果是在AndroidManifest.xml中註冊的接收器,在發送的時候需要多調用一個setComponent()
方法,其中第一個參數是包名,第二個參數是接收器的類名。
...
Intent intent=new Intent("com.example.k.androidpractice_1.MY_BROADCAST");
intent.setComponent(new ComponentName("com.example.k.androidpractice_1","com.example.k.androidpractice_1.MyBootReceiver"));
sendBroadcast(intent);
...
動態註冊
在代碼中動態註冊的接收器,就不需要調用這個方法了,直接send Intent即可。
Intent intent=new Intent("com.example.k.androidpractice_1.FORCE_LOGOUT");
sendBroadcast(intent);
目前我發現是這樣,也只是發現解決方法,不太知道其中的原理之類的,有大佬樂意的話可以指點一二也感激不盡。