问题
I have developed a music related android application. I have a problem in handling the mediaplayer on incoming call. I want to pause the audio during the phonecall and resume it back after the call gets ended. I need suggestions whether to use TelephonyManager with onstatechanged to pause and resume the audio (OR ) any other methods to pause and resume the application itself during Incoming calls.
回答1:
use onPause()
and onResume()
methods in your activity. When an incoming call comes, onPause() method is called. and onResume() is called when call is hung up.
This will work even if the user clicks on a notification sent from some other app.
回答2:
Here you go
Include following permission in manifest.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Then
PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
Play music
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
Pause music
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
And be a good android citizen by unregistering it in onDestroy
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
When user will pick up call then CALL_STATE_OFFHOOK
will get called.There you can write the code to pause playback.
来源:https://stackoverflow.com/questions/13377852/handling-incoming-calls-in-android-application