android9.0之前
//获取到ServiceManager
Class<?> clazz = Class.forName("android.os.ServiceManager");
//获取到ServiceManager里面的方法
Method method = clazz.getDeclaredMethod("getService", String.class);
//通过反射的方法调用方法
IBinder iBinder = (IBinder) method.invoke(null, TELEPHONY_SERVICE);
//注意:ITelephony的包名必须是com.android.internal.telephony,不能随便改的
//需要创建idle文件
ITelephony iTelephony = ITelephony.Stub.asInterface(iBinder);
int start = iTelephony.getCallState();
iTelephony.endCall();
android9.0之后 android 将MODIFY_PHONE_STATE升级为系统权限 以上方法无法获取权限,可通过一下方法解决
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
if (tm != null) {
if (checkSelfPermission(Manifest.permission.ANSWER_PHONE_CALLS) != PackageManager.PERMISSION_GRANTED) {
return;
}
boolean success = tm.endCall();
}
}