在我的应用程序中有一个BroadCastReceiver来处理来电。当有来电时,我会调用一些本机代码方法。我不希望在刷卡后杀死应用程序时调用此广播接收器。即使我杀了我的应用程序,接收器也会被调用。 接收器的代码是 -
public class CallReceiver extends BroadcastReceiver{
private final String TAG = this.getClass().getSimpleName();
private Context context;
public CallReceiver(){
}
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "In onReceive of CallReceiver");
this.context = context;
try {
// Telephony manager object to register for the listener
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// Initialising the MyPhoneStateListener class
MyPhoneStateListener PhoneListener = new MyPhoneStateListener();
// Register listener for LISTEN_CALL_STATE
telephonyManager.listen(PhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
} catch (Exception e) {
Log.e("Phone Receive Error", " " + e);
}
}
private class MyPhoneStateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state){
case TelephonyManager.CALL_STATE_OFFHOOK:
// This state denotes that the mobile is busy in some call
GLLib.pause(true);
Log.e(TAG, "Phone busy");
break;
case TelephonyManager.CALL_STATE_RINGING:
// This state denotes that the phone is ringing
GLLib.pause(true);
Log.e(TAG, "Phone ringing");
break;
case TelephonyManager.CALL_STATE_IDLE:
// This state denoted that the phone is idle
GLLib.pause(false);
Log.e(TAG, "Phone idle");
break;
}
super.onCallStateChanged(state, incomingNumber);
}
}
}
在清单中我有 -
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
许可是 -
答案 0 :(得分:1)
广播接收器与您的应用程序的生命周期无关,Android会读取您的应用程序的清单,并将广播发送到期望特定操作的相应应用程序。如果您希望在App未处于活动状态时停止接收广播,则需要在活动/服务的onDestroy中取消注册广播
unregisterReceiver(BroadcastReceiver receiver)
答案 1 :(得分:0)
解决问题的最简单方法是
Register BroadCastReceiver in onResume, unregister in onPause
希望这对你有用。