2016-09-09 67 views
-1

我想在Android中編寫一些可以檢測電話號碼和狀態的代碼。在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> 

回答

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(); 
    } 

}