我正在尝试接收呼叫状态更改事件(传入,传出)。在模拟器中,它确实工作正常,但是在设备中,它仅在应用程序运行状态下工作。我在 Sumsung S6 中尝试过,并且如果我删除了最近使用的应用程序(正在滑动),则广播接收器根本无法工作,我该如何使其正常工作?感谢您的帮助。
void speak();
<receiver
android:name=".utils.CallReceiver"
android:directBootAware="true"
android:enabled="true"
android:exported="true"
android:label="CallReceiver">
<intent-filter android:priority="101">
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
<!-- For pre-N devices -->
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter android:priority="100">
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
这是广播接收机从活动开始的代码
@Override
public void onReceive(Context context, Intent intent) {
Log.e("onCallStateChanged","intent state Detected");
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
}else if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ContextCompat.startForegroundService(context,new Intent(context, AppsLoggingService.class));
Log.e("Broadcast","Oreo Boot_completed");
} else {
context.startService(new Intent(context, AppsLoggingService.class));
Log.e("Broadcast","Boot_completed");
}
}else if (intent.getAction().equals("android.intent.action.PHONE_STATE")){
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
state = TelephonyManager.CALL_STATE_IDLE;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
state = TelephonyManager.CALL_STATE_OFFHOOK;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
state = TelephonyManager.CALL_STATE_RINGING;
}
onCallStateChanged(context, state, number);
}
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(call_boot_broadcast,intentFilter);
}
@Override
protected void onPause() {
unregisterReceiver(call_boot_broadcast);
super.onPause();
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onTaskRemoved(intent);
// registerScreenOffReceiver();
m_ScreenOffReceiver= new CallReceiver();
intentFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
// Add network connectivity change action.
intentFilter.addAction("android.intent.action.BOOT_COMPLETED");
intentFilter.addAction("android.intent.action.NEW_OUTGOING_CALL");
intentFilter.addAction("android.intent.action.PHONE_STATE");
// Set broadcast receiver priority.
intentFilter.setPriority(100);
this.registerReceiver(m_ScreenOffReceiver, intentFilter);
Log.e("Apploging","Apploggingservice started");
return START_STICKY;
}