Add these permissions:
<uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
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;
}