End call in android programmatically

I see a lot of questions that it's impossible to end call programmatically in Android. At the same time, I see a lot of dialer apps in googleplay market where you can activate the call and drop it also. How do they work?

Edit: I've read somewhere that my app has to be system app. Then how to make it system, and what is the difference between system and user apps?


Solution 1:

You do not need to be a system app. First, 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();     

void answerRingingCall();      

void silenceRinger(); 

}

Once you have that, you can use this code to end a call:

TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
Class clazz = Class.forName(telephonyManager.getClass().getName());
Method method = clazz.getDeclaredMethod("getITelephony");
method.setAccessible(true);
ITelephony telephonyService = (ITelephony) method.invoke(telephonyManager);
telephonyService.endCall();

You could use this inside a PhoneStateListener, for example. For this to work, you require permissions in manifest:

<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Edit: Apologies for horrible formatting, I still can't figure out how to properly do code blocks here :/

Solution 2:

For Android P (since Beta 2) and above, there is finally a formal API for endCall:

https://developer.android.com/reference/android/telecom/TelecomManager#endCall()

The ANSWER_PHONE_CALLS permission is required in manifest:

<uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />

With the permission, for API level 28 or above:

TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);

if (tm != null) {
    boolean success = tm.endCall();
    // success == true if call was terminated.
}

At the same time the original endCall() method under TelephonyManager is now protected by MODIFY_PHONE_STATE permission, and can no longer be invoked by non-system Apps by reflection without the permission (otherwise a Security Exception will be triggered).