我正在使用此代码,以收听手机的状态。当呼叫到达时它会暂停媒体播放器,但是一旦我接听电话,它就会从收听扬声器(而不是振铃器)开始播放。我也尝试从mediaPlayer.start()
移除case TelephonyManager.CALL_STATE_IDLE:
,在这种情况下,它工作正常,但它不会再次启动(恢复)。有没有可用的旗帜?
private final PhoneStateListener phoneListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
try {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
Toast.makeText(context, "Call is Coming",Toast.LENGTH_SHORT).show();
mediaPlayer.pause();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
break;
case TelephonyManager.CALL_STATE_IDLE:
mediaPlayer.start();
break;
default:
}
} catch (Exception ex) {
mediaPlayer.release();
}
}
};
}
或者还有其他办法吗?
答案 0 :(得分:1)
试试这个:
PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//Incoming call: Pause music
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not in call: Play music
} 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);
}