android电话拦截

时间:2022-04-25
本文章向大家介绍android电话拦截,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

其实大家可以下载 xxx卫士看下,它设置来电拒接模式后,都是会启动设置MMI指令的界面。然后再去“设置->通话设置->来电转接”,看看 “占线时转接” 设置好的电话号码,就可以知道空号/已关机/已停机对应的电话号码是什么了。

 1、修改一下BLOCKED_NUMBER这个变量值,把它设置为你要测试拦截的电话号码。

 2、全部功能是在一个Activity里实现的,所以大家要先运行这个Activity,然后点击“设置呼叫转移”,设置好呼叫转移后,不要关闭这个Activity,关了就拦截不了电话了。有心的朋友可以自己去写一个Service在后台运行拦截功能。

实现方式1:

       代码如下:

Java代码

  1. package net.toeach.android.callforwarding;     
  2. import java.lang.reflect.Method;     
  3. import android.app.Activity;     
  4. import android.content.BroadcastReceiver;     
  5. import android.content.Context;     
  6. import android.content.Intent;     
  7. import android.content.IntentFilter;     
  8. import android.media.AudioManager;     
  9. import android.net.Uri;     
  10. import android.os.Bundle;     
  11. import android.os.Handler;     
  12. import android.os.Message;     
  13. import android.os.RemoteException;     
  14. import android.telephony.TelephonyManager;     
  15. import android.util.Log;     
  16. import android.view.View;     
  17. import android.view.View.OnClickListener;     
  18. import com.android.internal.telephony.ITelephony;     
  19. /**  
  20.  * 演示如何设置呼叫转移,拦截电话(拦截后提示为空号)的例子  
  21.  * @author Tony from ToEach.  
  22.  * @email wan1976@21cn.com  
  23.  */
  24. public class MainActivity extends Activity {     
  25. private static final String TAG = MainActivity.class.getSimpleName();     
  26. private final static int OP_REGISTER = 100;     
  27. private final static int OP_CANCEL = 200;     
  28. private final static String BLOCKED_NUMBER = "1892501xxxx";//要拦截的号码  
  29. //占线时转移,这里13800000000是空号,所以会提示所拨的号码为空号  
  30. private final String ENABLE_SERVICE = "tel:**67*13800000000%23";     
  31. //占线时转移  
  32. private final String DISABLE_SERVICE = "tel:%23%2367%23";     
  33. private IncomingCallReceiver mReceiver;     
  34. private ITelephony iTelephony;     
  35. private AudioManager mAudioManager;     
  36. @Override
  37. public void onCreate(Bundle savedInstanceState) {     
  38. super.onCreate(savedInstanceState);     
  39.         setContentView(R.layout.main);     
  40.         findViewById(R.id.btnEnable).setOnClickListener(new OnClickListener(){     
  41. public void onClick(View v) {     
  42. //设置呼叫转移  
  43.           Message message = mHandler.obtainMessage();     
  44.     message.what = OP_REGISTER;     
  45.     mHandler.dispatchMessage(message);     
  46.    }     
  47.         });     
  48.         findViewById(R.id.btnDisable).setOnClickListener(new OnClickListener(){     
  49. public void onClick(View v) {     
  50. //取消呼叫转移  
  51.              Message message = mHandler.obtainMessage();     
  52.        message.what = OP_CANCEL;     
  53.        mHandler.dispatchMessage(message);     
  54.    }     
  55.         });     
  56.         mReceiver = new IncomingCallReceiver();     
  57.   IntentFilter filter = new IntentFilter("android.intent.action.PHONE_STATE");         
  58.         registerReceiver(mReceiver, filter);// 注册BroadcastReceiver   
  59.         mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);     
  60. //利用反射获取隐藏的endcall方法  
  61.         TelephonyManager telephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);     
  62. try {     
  63.    Method getITelephonyMethod = TelephonyManager.class.getDeclaredMethod("getITelephony", (Class[]) null);     
  64.    getITelephonyMethod.setAccessible(true);     
  65.    iTelephony = (ITelephony) getITelephonyMethod.invoke(telephonyMgr, (Object[]) null);     
  66.      } catch (Exception e) {     
  67.       e.printStackTrace();     
  68.      }     
  69.     }     
  70. private Handler mHandler = new Handler() {     
  71. public void handleMessage(Message response) {     
  72. int what = response.what;     
  73. switch(what) {     
  74. case OP_REGISTER:{     
  75.         Intent i = new Intent(Intent.ACTION_CALL);     
  76.               i.setData(Uri.parse(ENABLE_SERVICE));     
  77.               startActivity(i);     
  78. break;     
  79.        }     
  80. case OP_CANCEL:{     
  81.         Intent i = new Intent(Intent.ACTION_CALL);     
  82.               i.setData(Uri.parse(DISABLE_SERVICE));     
  83.               startActivity(i);     
  84. break;     
  85.        }     
  86.       }     
  87.   }     
  88.  };     
  89. private class IncomingCallReceiver extends BroadcastReceiver{     
  90. @Override
  91. public void onReceive(Context context, Intent intent) {     
  92.    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);     
  93.          Log.i(TAG, "State: "+ state);     
  94.    String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);     
  95.          Log.d(TAG, "Incomng Number: " + number);     
  96. if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)){//电话正在响铃            
  97. if(number.equals(BLOCKED_NUMBER)){//拦截指定的电话号码  
  98. //先静音处理  
  99.            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);     
  100.            Log.d(TAG, "Turn ringtone silent");     
  101. try {     
  102. //挂断电话  
  103.       iTelephony.endCall();     
  104.      } catch (RemoteException e) {     
  105.       e.printStackTrace();     
  106.      }     
  107. //再恢复正常铃声  
  108.                  mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);     
  109.           }     
  110.          }     
  111.   }     
  112.  }     
  113. }    

       AndroidManifest.xml如下:

XML/HTML代码

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android "
  3. package="net.toeach.android.callforwarding"
  4. android:versionCode="1"
  5. android:versionName="1.0">
  6. <application android:icon="@drawable/icon" android:label="@string/app_name">
  7. <activity android:name=".MainActivity"
  8. android:label="@string/app_name">
  9. <intent-filter>
  10. <action android:name="android.intent.action.MAIN" />
  11. <category android:name="android.intent.category.LAUNCHER" />
  12. </intent-filter>
  13. </activity>
  14. </application>
  15. <uses-sdk android:minSdkVersion="8" />
  16. <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
  17. <uses-permission android:name="android.permission.CALL_PHONE"/>
  18. </manifest>

实现方式2:

       1、建立包android.refuseCalling。

       refuseCalling.java代码如下:

Java代码

  1. package android.refuseCalling;     
  2. import android.app.Activity;     
  3. import android.net.Uri;     
  4. import android.os.Bundle;     
  5. import java.lang.reflect.InvocationTargetException;     
  6. import java.lang.reflect.Method;     
  7. import android.content.Context;     
  8. import android.content.Intent;     
  9. import android.os.RemoteException;     
  10. import android.telephony.PhoneStateListener;     
  11. import android.telephony.TelephonyManager;     
  12. import android.util.Log;     
  13. import android.widget.TextView;     
  14. import com.android.internal.telephony.ITelephony;     
  15. public class refuseCalling extends Activity {     
  16. private static final String TAG = "Telephony";     
  17. private TextView view = null;     
  18. private TelephonyManager tManager = null;     
  19. private ITelephony iTelephony  = null;     
  20. //占线时转移,提示所拨的号码为空号  
  21. private final String ENABLE_SERVICE = "tel:**67*13800000000%23";     
  22. //占线时转移,提示所拨的号码为关机  
  23. private final String ENABLE_POWEROFF_SERVICE = "tel:**67*13810538911%23";     
  24. //占线时转移,提示所拨的号码为停机  
  25. private final String ENABLE_STOP_SERVICE = "tel:**21*13701110216%23";     
  26. //占线时转移  
  27. private final String DISABLE_SERVICE = "tel:%23%2321%23";     
  28. @Override
  29. protected void onCreate(Bundle savedInstanceState) {     
  30. super.onCreate(savedInstanceState);     
  31. //打开监听电话功能  
  32.         TelephonyManager mTelephonyMgr = (TelephonyManager) this
  33.                 .getSystemService(Context.TELEPHONY_SERVICE);     
  34.         mTelephonyMgr.listen(new TeleListener(),     
  35.                 PhoneStateListener.LISTEN_CALL_STATE);     
  36. //gui  
  37.         view = new TextView(this);     
  38.         view.setText("listen the state of phonen");     
  39.         setContentView(view);     
  40.         tManager = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);     
  41. //初始化iTelephony  
  42.         Class <TelephonyManager> c = TelephonyManager.class;     
  43.         Method getITelephonyMethod = null;     
  44. try {     
  45.         getITelephonyMethod = c.getDeclaredMethod("getITelephony", (Class[])null);     
  46.         getITelephonyMethod.setAccessible(true);     
  47.         } catch (SecurityException e) {     
  48. // TODO Auto-generated catch block  
  49.         e.printStackTrace();     
  50.         } catch (NoSuchMethodException e) {     
  51. // TODO Auto-generated catch block  
  52.         e.printStackTrace();     
  53.         }     
  54. try {     
  55.         iTelephony = (ITelephony) getITelephonyMethod.invoke(tManager, (Object[])null);     
  56.         } catch (IllegalArgumentException e) {     
  57. // TODO Auto-generated catch block  
  58.         e.printStackTrace();     
  59.         } catch (IllegalAccessException e) {     
  60. // TODO Auto-generated catch block  
  61.         e.printStackTrace();     
  62.         } catch (InvocationTargetException e) {     
  63. // TODO Auto-generated catch block  
  64.         e.printStackTrace();     
  65.         }     
  66. //启用空号提示  
  67.         Intent i = new Intent(Intent.ACTION_CALL);     
  68.         i.setData(Uri.parse(ENABLE_STOP_SERVICE));     
  69.         startActivity(i);     
  70.         Log.v(TAG, "启用空号提示");     
  71.     }     
  72. class TeleListener extends PhoneStateListener {     
  73. @Override
  74. public void onCallStateChanged(int state, String incomingNumber) {     
  75. super.onCallStateChanged(state, incomingNumber);     
  76. switch (state) {     
  77. case TelephonyManager.CALL_STATE_IDLE: {     
  78.                 Log.e(TAG, "CALL_STATE_IDLE");     
  79.                 view.append("CALL_STATE_IDLE " + "n");     
  80. break;     
  81.             }     
  82. case TelephonyManager.CALL_STATE_OFFHOOK: {     
  83.                 Log.e(TAG, "CALL_STATE_OFFHOOK");     
  84.                 view.append("CALL_STATE_OFFHOOK" + "n");     
  85. break;     
  86.             }     
  87. case TelephonyManager.CALL_STATE_RINGING: {     
  88.                 Log.e(TAG, "CALL_STATE_RINGING");     
  89.                 view.append("CALL_STATE_RINGING" + "n");     
  90. try {     
  91.                     iTelephony.endCall();                         
  92.                 } catch (RemoteException e1) {     
  93. // TODO Auto-generated catch block  
  94.                     e1.printStackTrace();     
  95.                 }                     
  96. break;     
  97.             }     
  98. default:     
  99. break;     
  100.             }     
  101.         }     
  102.     }     
  103. protected void onStop() {     
  104. super.onStop();     
  105.         }     
  106. protected void onDestroy() {     
  107. super.onDestroy();     
  108.         finish();     
  109.         Intent i = new Intent(Intent.ACTION_CALL);     
  110.         i.setData(Uri.parse(DISABLE_SERVICE));     
  111.         startActivity(i);     
  112.         }     
  113. }    

       2、建立包android.telephony。

       NeighboringCellInfo.aidl代码如下:

       package android.telephony;

       3、建立包 com.android.internal.telephony。

       ITelephony.aidl代码如下:

Java代码

  1. /*  
  2.  *  
  3.  * Licensed under the  android License, Version 2.0 (the "License");  
  4.  * you may not use this file except in compliance with the License.  
  5.  * You may obtain a copy of the License at  
  6.  *  
  7.  *      http://www.apache.org/licenses/LICENSE-2.0  
  8.  *  
  9.  * Unless required by applicable law or agreed to in writing, software  
  10.  * distributed under the License is distributed on an "AS IS" BASIS,  
  11.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  12.  * See the License for the specific language governing permissions and  
  13.  * limitations under the License.  
  14.  */
  15. package com.android.internal.telephony;     
  16. import android.os.Bundle;     
  17. import java.util.List;     
  18. import android.telephony.NeighboringCellInfo;     
  19. //import com.FrameSpeed.NeighboringCellInfo;  
  20. /**  
  21.  * Interface used to interact with the phone.  Mostly this is used by the  
  22.  * TelephonyManager class.  A few places are still using this directly.  
  23.  * Please clean them up if possible and use TelephonyManager insteadl.  
  24.  *  
  25.  * {@hide}  
  26.  */
  27. interface ITelephony {     
  28. /**  
  29.      * Dial a number. This doesn't place the call. It displays  
  30.      * the Dialer screen.  
  31.      * @param number the number to be dialed. If null, this  
  32.      * would display the Dialer screen with no number pre-filled.  
  33.      */
  34. void dial(String number);    
  35. /**  
  36.      * Place a call to the specified number.  
  37.      * @param number the number to be called.  
  38.      */
  39. void call(String number);     
  40. /**  
  41.      * If there is currently a call in progress, show the call screen.  
  42.      * The DTMF dialpad may or may not be visible initially, depending on  
  43.      * whether it was up when the user last exited the InCallScreen.  
  44.      *  
  45.      * @return true if the call screen was shown.  
  46.      */
  47. boolean showCallScreen();     
  48. /**  
  49.      * Variation of showCallScreen() that also specifies whether the  
  50.      * DTMF dialpad should be initially visible when the InCallScreen  
  51.      * comes up.  
  52.      *  
  53.      * @param showDialpad if true, make the dialpad visible initially,  
  54.      *                    otherwise hide the dialpad initially.  
  55.      * @return true if the call screen was shown.  
  56.      *  
  57.      * @see showCallScreen  
  58.      */
  59. boolean showCallScreenWithDialpad(boolean showDialpad);     
  60. /**  
  61.      * End call if there is a call in progress, otherwise does nothing.  
  62.      *  
  63.      * @return whether it hung up  
  64.      */
  65. boolean endCall();     
  66. /**  
  67.      * Answer the currently-ringing call.  
  68.      *  
  69.      * If there's already a current active call, that call will be  
  70.      * automatically put on hold.  If both lines are currently in use, the  
  71.      * current active call will be ended.  
  72.      *  
  73.      * TODO: provide a flag to let the caller specify what policy to use  
  74.      * if both lines are in use.  (The current behavior is hardwired to  
  75.      * "answer incoming, end ongoing", which is how the CALL button  
  76.      * is specced to behave.)  
  77.      *  
  78.      * TODO: this should be a oneway call (especially since it's called  
  79.      * directly from the key queue thread).  
  80.      */
  81. void answerRingingCall();     
  82. /**  
  83.      * Silence the ringer if an incoming call is currently ringing.  
  84.      * (If vibrating, stop the vibrator also.)  
  85.      *  
  86.      * It's safe to call this if the ringer has already been silenced, or  
  87.      * even if there's no incoming call.  (If so, this method will do nothing.)  
  88.      *  
  89.      * TODO: this should be a oneway call too (see above).  
  90.      *       (Actually *all* the methods here that return void can  
  91.      *       probably be oneway.)  
  92.      */
  93. void silenceRinger();     
  94. /**  
  95.      * Check if we are in either an active or holding call  
  96.      * @return true if the phone state is OFFHOOK.  
  97.      */
  98. boolean isOffhook();     
  99. /**  
  100.      * Check if an incoming phone call is ringing or call waiting.  
  101.      * @return true if the phone state is RINGING.  
  102.      */
  103. boolean isRinging();     
  104. /**  
  105.      * Check if the phone is idle.  
  106.      * @return true if the phone state is IDLE.  
  107.      */
  108. boolean isIdle();     
  109. /**  
  110.      * Check to see if the radio is on or not.  
  111.      * @return returns true if the radio is on.  
  112.      */
  113. boolean isRadioOn();     
  114. /**  
  115.      * Check if the SIM pin lock is enabled.  
  116.      * @return true if the SIM pin lock is enabled.  
  117.      */
  118. boolean isSimPinEnabled();     
  119. /**  
  120.      * Cancels the missed calls notification.  
  121.      */
  122. void cancelMissedCallsNotification();     
  123. /**  
  124.      * Supply a pin to unlock the SIM.  Blocks until a result is determined.  
  125.      * @param pin The pin to check.  
  126.      * @return whether the operation was a success.  
  127.      */
  128. boolean supplyPin(String pin);     
  129. /**  
  130.      * [ASD2-ES1|Connice|2011.04.14]  
  131.      */
  132. boolean supplyPuk(String puk, String pin);     
  133. /**  
  134.      * Handles PIN MMI commands (PIN/PIN2/PUK/PUK2), which are initiated  
  135.      * without SEND (so <code>dial</code> is not appropriate).  
  136.      *  
  137.      * @param dialString the MMI command to be executed.  
  138.      * @return true if MMI command is executed.  
  139.      */
  140. boolean handlePinMmi(String dialString);   
  141. /**  
  142.      * Toggles the radio on or off.  
  143.      */
  144. void toggleRadioOnOff();     
  145. /**  
  146.      * Set the radio to on or off  
  147.      */
  148. boolean setRadio(boolean turnOn);     
  149. /**  
  150.      * Request to update location information in service state  
  151.      */
  152. void updateServiceLocation();     
  153. /**  
  154.      * Enable location update notifications.  
  155.      */
  156. void enableLocationUpdates();     
  157. /**  
  158.      * Disable location update notifications.  
  159.      */
  160. void disableLocationUpdates();     
  161. /**  
  162.      * Enable a specific APN type.  
  163.      */
  164. int enableApnType(String type);     
  165. /**  
  166.      * Disable a specific APN type.  
  167.      */
  168. int disableApnType(String type);     
  169. /**  
  170.      * Allow mobile data connections.  
  171.      */
  172. boolean enableDataConnectivity();     
  173. /**  
  174.      * Disallow mobile data connections.  
  175.      */
  176. boolean disableDataConnectivity();     
  177. /**  
  178.      * Report whether data connectivity is possible.  
  179.      */
  180. boolean isDataConnectivityPossible();     
  181.     Bundle getCellLocation();     
  182. /**  
  183.      * Returns the neighboring cell information of the device.  
  184.      */
  185.     List<NeighboringCellInfo> getNeighboringCellInfo();     
  186. int getCallState();     
  187. int getDataActivity();     
  188. int getDataState();     
  189. /**  
  190.      * Returns the current active phone type as integer.  
  191.      * Returns TelephonyManager.PHONE_TYPE_CDMA if RILConstants.CDMA_PHONE  
  192.      * and TelephonyManager.PHONE_TYPE_GSM if RILConstants.GSM_PHONE  
  193.      */
  194. int getActivePhoneType();     
  195. /**  
  196.      * Returns the CDMA ERI icon index to display  
  197.      */
  198. int getCdmaEriIconIndex();     
  199. /**  
  200.      * Returns the CDMA ERI icon mode,  
  201.      * 0 - ON  
  202.      * 1 - FLASHING  
  203.      */
  204. int getCdmaEriIconMode();     
  205. /**  
  206.      * Returns the CDMA ERI text,  
  207.      */
  208.     String getCdmaEriText();     
  209. /**  
  210.      * Returns true if OTA service provisioning needs to run.  
  211.      * Only relevant on some technologies, others will always  
  212.      * return false.  
  213.      */
  214. boolean needsOtaServiceProvisioning();     
  215. /**  
  216.       * Returns the unread count of voicemails  
  217.       */
  218. int getVoiceMessageCount();     
  219. /**  
  220.       * Returns the network type  
  221.       */
  222. int getNetworkType();     
  223. /**  
  224.      * Return true if an ICC card is present  
  225.      */
  226. boolean hasIccCard();     
  227. }     
  228. parcelable NeighboringCellInfo;   

       4、AndroidManifest.xml代码如下:

XML/HTML代码

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
 package="android.refuseCalling" 
 android:versionCode="1" 
 android:versionName="1.0"> 
 <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
 <uses-permission android:name="android.permission.CALL_PHONE" /> 
 <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" /> 
 
 <application android:icon="@drawable/icon" android:label="@string/app_name"> 
 <activity android:name=".refuseCalling" 
 android:label="@string/app_name"> 
 <intent-filter> 
 <action android:name="android.intent.action.MAIN" /> 
 <category android:name="android.intent.category.LAUNCHER" /> 
 </intent-filter> 
 </activity> 
 
 </application> 
</manifest>