Handling Android application pause on incoming call and resume after call end

前端 未结 2 606
无人共我
无人共我 2020-12-30 16:41

I want to pause my android application when the phone receives an incoming call. After the call ends, I want my applications to resume automatically.

How would this

2条回答
  •  爱一瞬间的悲伤
    2020-12-30 17:24

    you have to implement a Listener for the PhoneState. I did this in a private Class:

    private class PhoneCallListener extends PhoneStateListener {
    
        private boolean isPhoneCalling = false;
    
        // needed for logging
        String TAG = "PhoneCallListener";
    
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
    
            if (TelephonyManager.CALL_STATE_RINGING == state) {
                // phone ringing
                Log.i(TAG, "RINGING, number: " + incomingNumber);
            }
    
            if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
                // active
                Log.i(TAG, "OFFHOOK");
    
                isPhoneCalling = true;
            }
    
            if (TelephonyManager.CALL_STATE_IDLE == state) {
                // run when class initial and phone call ended,
                // need detect flag from CALL_STATE_OFFHOOK
                Log.i(TAG, "IDLE");
    
                if (isPhoneCalling) {
    
                    Log.i(TAG, "restart app");
    
                    // restart call application
                    Intent i = getBaseContext().getPackageManager()
                            .getLaunchIntentForPackage(
                                    getBaseContext().getPackageName());
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                            | Intent.FLAG_ACTIVITY_CLEAR_TOP
                            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(i);
    
                    isPhoneCalling = false;
                }
    
            }
    
    
    }
    }
    

    and you need to add the permission to the Manifest-File

    
    

提交回复
热议问题