該應用程序偵聽來電,然後停止播放音樂。然後,我希望音樂在通話結束後重新開始。但我在CALL_STATE_IDLE
上遇到問題,因爲它在應用程序啓動時檢測到,所以在其方法內的任何調用都將在應用程序啓動時調用。如何防止應用程序啓動時檢測到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
中,我如何註冊一些聽衆?
如果您的應用尚未暫停播放,請忽略CALL_STATE_IDLE。 – Michael
@Michael像在我貼的代碼中,或者有更好的方法? – sandalone