应用程序侦听来电,然后停止播放音乐。然后,我希望在通话结束后重启音乐。但我遇到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
?
答案 0 :(得分:2)
我找到了替代解决方案。随意使用它。如果有人有更好的,可以随意与社区分享。
private void listenForIncomingCall() {
PhoneStateListener phoneStateListener = new PhoneStateListener() {
boolean toTrack = false; //to prevent triggering in onCreate
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//Incoming call: Pause music
doSomething();
} else if (state == TelephonyManager.CALL_STATE_IDLE) {
//Not in call: Play music
if (toTrack) {
doSomething();
}
toTrack = true;
} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
if (toTrack) {
doSomething();
}
toTrack = true;
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mgr != null)
{
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}