1、监听手机的状态是经常要用到的,当正在录音或者正在播放音乐的时候想要监听手机是否处于拨打电话的情况,这时候可以采取下面的办法。
变量的声明:
private TelephonyManager mTelephonyManager;
private PhoneStateListener mPhoneStateListener;
在onCreate()方法中先声明:
mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mPhoneStateListener = getPhoneStateListener();
在onResume()方法中程序运行过程中监听手机状态
protected void onResume() {
super.onResume();
// While we're in the foreground, listen for phone state changes.
mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
在onPause()方法中监听程序暂停时候的手机状态
// Stop listening for phone state changes.
mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
mSampleInterrupted = mRecorder.state() == Recorder.RECORDING_STATE;
注册监听
private PhoneStateListener getPhoneStateListener() {
PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String ignored) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
if ((sOldCallState == TelephonyManager.CALL_STATE_OFFHOOK)
&& !(mAudioSourceType == MediaRecorder.AudioSource.MIC)){
mRecorder.stop();
showStoppedNotification();
mAudioSourceType = MediaRecorder.AudioSource.MIC;
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
sOldCallState = TelephonyManager.CALL_STATE_OFFHOOK;
break;
default:
// The control should not come here
Log.e(TAG,"Unknown call state");
break;
}
}
};
return phoneStateListener;
}