簡體   English   中英

從android中的另一個廣播接收器注冊廣播接收器

[英]Register Broadcast Receiver from another Broadcast Receiver in android

目前我有用於收聽呼叫狀態事件的廣播接收器。 我在AndroidManifest.xml注冊了Broadcast Receiver,如下所示。

<receiver android:name=".api.PhoneCallReceiver">
     <intent-filter>
          <action android:name="android.intent.action.PHONE_STATE" />
     </intent-filter>
</receiver>

當應用程序啟動時,此廣播接收器已注冊為偵聽呼叫狀態事件,並且根據CALL_STATE我正在管理我的應用程序。

手機重啟后工作正常。 手機重啟后,此廣播接收器停止工作。 我知道我必須注冊接收器以監聽系統的BOOT_COMPLETED事件。

我所做的如下所示:

<receiver android:name=".api.PhoneCallReceiver">
     <intent-filter>
          <action android:name="android.intent.action.PHONE_STATE" />
     </intent-filter>
     <intent-filter>
          <action android:name="android.intent.action.BOOT_COMPLETED" />
     </intent-filter>
</receiver>

我還獲得了獲取BOOT_COMPLETED系統事件的權限。

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

但不知怎的,它不起作用。 我正在考慮制作只BOOT_COMPLETED事件的新廣播接收器,但問題就在BOOT_COMPLETED

所以我的問題是,當有來電時我怎么能啟動這個電話呼叫監聽器廣播接收器?

如何從另一個廣播接收器注冊廣播接收器

我是否必須將現有的廣播接收器代碼移至服務中,以便我可以從Boot Receiver啟動服務?

任何幫助將不勝感激。

歡迎任何其他答案。

我已經通過創建新的廣播接收器和onReceive()方法解決了這個問題,當手機重新啟動時我將動態注冊READ_PHONE_STATE廣播接收器,這也是明顯的注冊接收器。

以下是代碼:

AndroidManifest.xml中:

<receiver android:name=".api.ServiceStarter">
     <intent-filter>
         <action android:name="android.intent.action.BOOT_COMPLETED" />
     </intent-filter>
</receiver>

廣播接收器:

public class ServiceStarter extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.PHONE_STATE");
        PhoneCallReceiver receiver = new PhoneCallReceiver();
        context.getApplicationContext().registerReceiver(receiver, filter);
    }
}

您必須使用以下應用程序上下文注冊接收器:

context.getApplicationContext().registerReceiver(receiver, filter);

代替

context.registerReceiver(receiver, filter);

否則你將得到以下異常:

java.lang.RuntimeException:無法啟動接收器com.ecosmob.contactpro.api.ServiceStarter:android.content.ReceiverCallNotAllowedException:不允許BroadcastReceiver組件注冊接收意圖

我希望它能幫助別人!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM