簡體   English   中英

PHONE_STATE 接收器不適用於基於上下文的接收器

[英]PHONE_STATE receiver not working with context-based receiver

我正在開發一個 android 應用程序,我想在其中獲取來電號碼,因此我創建了一個基於上下文的receiver並將其注冊到我的MainActivity中。 但是無論應用程序是在foreground還是background ,我的接收器都不會被觸發。 我檢查了 Android 文檔,他們提到您應該為Android 8.0+使用基於上下文的接收器,但他們尚未為PHONE_STATE廣播接收器設置此例外,但我使用基於上下文只是為了安全起見。 這就是我注冊接收器的方式:

private void registerMyReceiver() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    Toast.makeText(context, "Receiver Triggered !!", Toast.LENGTH_SHORT).show();
                }
            };
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("android.intent.action.PHONE_STATE");
            this.registerReceiver(broadcastReceiver, intentFilter);

        }

    }

我什至也要求運行時權限:

private void grantPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 0);
        }
    }

提前致謝。

另一種方法:

TelephonyManager systemService = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    if (systemService == null)
        return;
    PhoneStateListener listener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String phoneNumber) {
            super.onCallStateChanged(state, phoneNumber);
        }
    };

    systemService.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);

需要許可:

android.permission.READ_PHONE_STATE

使用廣播:

<receiver android:name="PhoneStateReceiver">
        <intent-filter android:priority="1000">
            <action android:name="android.intent.action.PHONE_STATE" />
            <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
            <action android:name="android.telecom.action.DEFAULT_CALL_SCREENING_APP_CHANGED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

在我的項目中。

在代碼中。

 IntentFilter intentFilter = new IntentFilter();
    intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
  ....//other actions.

試試這個。

希望能幫到你。

暫無
暫無

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

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