I am developing an android app to block the incoming calls. Till API 27 (OREO MR1), I have used the reflection method (iTelephony) to block the incoming calls. But in Android Pie, reflections are deprecated. So the iTelephony method is not working in Android P version. Is there any working method to block incoming call in API >= 28.
In Android Pie, there is an official way to block the incoming calls using endcall()
function in TelecomManager,
https://developer.android.com/reference/android/telecom/TelecomManager#endCall()
To use this function you need ANSWER_PHONE_CALLS
permission. This is categorized as dangerous permission, so you need to request this permission during runtime instead of adding in manifest file.
if (checkSelfPermission(Manifest.permission.ANSWER_PHONE_CALLS) == PackageManager.PERMISSION_GRANTED) {
TelecomManager tcm = (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
if (tcm != null) {
try {
if (incomingCallNumber != null) {
tcm.endCall();
Log.d(TAG, "Incoming Call Blocked " + incomingCallNumber);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
EDIT: endcall() function is deprecated in Android Q (API 29), so you can use this method only in Android Pie (API 28).
My APP compile targetSdkVersion 22, In order to avoid dynamic application permissions,In order to avoid dynamically applying for permissions, but I cannot use endcall, the system prompts that there is no permission
android.permission.ANSWER_PHONE_CALLS
For the Android version less then or equal to 27, use the below code
iTelephony.java
public interface ITelephony { boolean endCall(); void answerRingingCall(); void silenceRinger(); }
CallBlocker.java
ITelephony telephonyService; TelephonyManager telephony; if (Build.VERSION.SDK_INT <= 27) { TelephonyManager tpm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (tpm != null) { try { Method m = tpm.getClass().getDeclaredMethod("getITelephony"); m.setAccessible(true); telephonyService = (ITelephony) m.invoke(tpm); if (incomingNumber != null && incomingNumbersList.contains(incomingNumber)) { telephonyService.silenceRinger(); telephonyService.endCall(); Log.d(TAG, "Incoming Call Ended " + incomingNumber); } } catch (Exception e) { e.printStackTrace(); } } }