拒绝Android中的电话号码

时间:2016-09-09 13:31:41

标签: android telephony phone-call

我想在Android中编写一些可以检测电话号码和状态的代码。

因此,当一个特定号码正在呼叫时(让我们说123456789),该应用拒绝该号码并结束通话。我该怎么办?

public class ReciveCalls extends BroadcastReceiver {
    public  void onReceive(Context context, Intent intent){
        if(intent.getAction().equals("android.intent.action.PHONE_STATE")){
            String state=intent.getStringExtra(TelephonyManager.EXTRA_STATE);
            String Number=intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
            Toast toast=Toast.makeText(context,"Number:"+Number+",state:"+state,Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP|Gravity.LEFT,3,0);
            toast.show();
        }
      }
}

清单:

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

1 个答案:

答案 0 :(得分:2)

您可以使用此代码:

public void onReceive(Context context, Intent intent) {
    // Get AudioManager
    this.context = context;
    // Get TelephonyManager
    telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            // Get incoming number
            incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
            if(incomingNumber) //check the number and reject the call
            {
                    rejectCall();
            }


        }
    }


}

使用以下方法拒绝来电:

 private void rejectCall() {
    try {

        // Get the getITelephony() method
        Class<?> classTelephony = Class.forName(telephonyManager.getClass().getName());
        Method method = classTelephony.getDeclaredMethod("getITelephony");
        // Disable access check
        method.setAccessible(true);
        // Invoke getITelephony() to get the ITelephony interface
        Object telephonyInterface = method.invoke(telephonyManager);
        // Get the endCall method from ITelephony
        Class<?> telephonyInterfaceClass = Class.forName(telephonyInterface.getClass().getName());
        Method methodEndCall = telephonyInterfaceClass.getDeclaredMethod("endCall");
        // Invoke endCall()
        methodEndCall.invoke(telephonyInterface);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}