java - PHONE_STATE 接收器无法与基于上下文的接收器一起使用

标签 java android

我正在开发一个 Android 应用程序,我想在其中获取来电号码,因此我创建了一个基于上下文的接收器并将其注册到我的MainActivity中。但无论应用程序是在前台还是后台,我的接收器都不会被触发。我检查了 Android 文档,他们提到您应该为 Android 8.0+ 使用基于上下文的接收器,但他们尚未为 PHONE_STATE 广播接收器设置此异常(exception),但我正在使用上下文-基于只是为了安全起见。 这就是我注册接收器的方式:

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.

试试这个。

希望能帮到你。

关于java - PHONE_STATE 接收器无法与基于上下文的接收器一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62056419/

相关文章:

android - 在 Android OrmLite 中使用多个数据库助手

Android:画廊像滑动效果

java - 在recyclerview中高效下载和使用图片

java - 将 war 重定向到主域?

java - 尝试打印从 L 到 R 的子数组的期望值(平均值)的下限

java - JPA - 创建交叉引用条目时出错 - 违反非空约束

java - 使用 PDFBox 将图像转换为 byte[]

android - 我可以在 Android 中使用不同的带有颜色的 xml 文件吗?

java - 如何将参数/参数传递给回调函数?

android - 无法测试应用内订阅