Disconnect incoming call programmatically in andro

2019-07-22 09:09发布

问题:

I'm going to use endCall method of ITelephony.aidl to disconnect all incoming calls programmatically.

This is my BroadcastReceiver:

public class CallBlocker extends BroadcastReceiver {

String number;

@Override
public void onReceive(Context context, Intent intent) {

    if (intent.getAction() != null && intent.getAction().equals("android.intent.action.PHONE_STATE")) {
        disconnectIncomingCall(context);
    }
}

private void disconnectIncomingCall(Context context) {
    ITelephony telephonyService;
    TelephonyManager telephony = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
    try {
        Class c = Class.forName(telephony.getClass().getName());
        Method m = c.getDeclaredMethod("getITelephony");
        m.setAccessible(true);
        IBinder binder = (IBinder) m.invoke(null, new Object[]{TELEPHONY_SERVICE});
        telephonyService = ITelephony.Stub.asInterface(binder);
        telephonyService.endCall();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

And this is my Service:

public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return new ITelephony.Stub() {
        @Override
        public boolean endCall() throws RemoteException {
            return false;
        }

        @Override
        public void answerRingingCall() throws RemoteException {

        }

        @Override
        public void silenceRinger() throws RemoteException {

        }
    };
}
}

And this is the ITelephony.aidl file:

package com.android.internal.telephony;

interface ITelephony {

boolean endCall();

void answerRingingCall();

void silenceRinger();

}

And I declared Service and BroadcastReceiver in Manifest.

When I run the project and I connect call, I get this error:

java.lang.NullPointerException: null receiver

On this line:

IBinder binder = (IBinder) m.invoke(null, new Object[]{TELEPHONY_SERVICE});

How can I solve this problem to block all incoming calls programmatically in android?