该应用程序会监听来电,然后停止播放音乐。然后,我希望音乐在通话结束后重新开始。但是我遇到了一个问题,CALL_STATE_IDLE
因为它在应用程序启动时被检测到,所以它的方法内的任何调用都会在应用程序启动时被调用。
我的代码如下所示:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
listenForIncomingCall();
...
}
private void listenForIncomingCall() {
PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//Incoming call: Pause music
//stop playing music
} else if (state == TelephonyManager.CALL_STATE_IDLE) {
//Not in call: Play music
//a code placed here activates on app starts
} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mgr != null)
{
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
我怎样才能防止这种情况?如果不在,我该如何注册一些听众onCreate
?