我正在开发一个 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/