Handling Incoming calls in android application

被刻印的时光 ゝ 提交于 2019-12-06 14:01:14

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.

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.

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