Handling Incoming calls in android application

无人久伴 提交于 2019-12-07 20:46:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!