How to end an incoming call programmatically on Android 8.0 Oreo

后端 未结 5 1990
北海茫月
北海茫月 2020-12-06 05:12

Up to Android 7.1 it was possible to end an incoming call by using the ITelephony.endCall() method and giving your app the permissions

5条回答
  •  悲哀的现实
    2020-12-06 06:16

    Add these permissions:

    
    
    

    Also ask for runtime permission for ANSWER_PHONE_CALLS and READ_CALL_LOG permissions (as they are Dangerous Permissions).

    For android oreo and below:

    Create package com.android.internal.telephony in your project, and put this in a file called "ITelephony.aidl":

    package com.android.internal.telephony; 
    interface ITelephony {      
        boolean endCall();     
    }
    

    For above android oreo:

    TelecomManager class provides direct method to end call(provided in code).

    After above steps add method provided below: (Before this make sure to initialize TelecomManager and TelephonyManager).

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        telecomManager = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
    }
    
    private boolean declinePhone() {
        if (telecomManager.isInCall()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                if (telecomManager != null) {
                    boolean success = telecomManager.endCall();
                    return success;
                }
            } else {
                try {
                    Class classTelephony = Class.forName(telephonyManager.getClass().getName());
                    Method methodGetITelephony = classTelephony.getDeclaredMethod("getITelephony");
                    methodGetITelephony.setAccessible(true);
                    ITelephony telephonyService = (ITelephony) methodGetITelephony.invoke(telephonyManager);
                    if (telephonyService != null) {
                        return telephonyService.endCall();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("LOG", "Cant disconnect call");
                    return false;
                }
            }
        }
        return false;
    }
    

提交回复
热议问题