標籤:android style blog color io os 使用 ar java
如何攔截來電,並檢測到某些特定號碼時自動掛斷電話?
使用反射的技術訪問android SDK的內部功能來掛斷電話
1.攔截來電的廣播接收器類(InCallReceiver)的onReceive()方法
1 public void onReceive(final Context context,Intent intent){ 2 //得到電話管理服務,以便獲得電話狀態 3 TelephonyManager tm=(TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE); 4 //根據不同的來電狀態進行處理 5 switch(tm.getCallState()){ 6 //響鈴 7 case TelephonyManager.CALL_STATE_RINGING: 8 //獲得來電的電話號碼 9 String incomingNumber=intent.getStringExtra("incoming_number");10 //假如來電號碼時12345678.則掛斷電話11 if("12345678".equals(incomingNumber)){12 Calss<TelephonyManager> telephonyManagerClass=TelephonyManager.class;13 //通過Java反射技術獲得getITelephony方法對應的Method對象14 Method telephonyMethod=telephonyManagerClass.getDelaredMethod("getITelephony",(Class[]) null);15 //允許訪問getITelephony方法16 telephonyMethod.setAccessible(true);17 //調用getITelephony方法擷取ITelephony對象18 Object obj=telephonyMethod.invoke(telephonyManager.(Object[]) null);19 //擷取endCall方法對應Method對象20 Method endCallMethod=obj.getClass().getMethod("endCall",null);21 //允許訪問endCall方法22 endCallMethod.setAccessible(true);23 //調用endCall方法掛斷電話24 endCallMethod.invoke(obj,null);25 26 }27 break;28 case TelephonyManager.CALL_STATE_OFFHOOK://電話中29 Log.d("call_state","offhook");30 break;31 case TelephonyManager.CALL_STATE_IDLE://掛斷電話32 closeToast();33 break;34 }35 }
2.最後需要在資訊清單檔中定義廣播接收器,並添加可接收來電廣播的許可權
配置inCallReceiver
1 <receiver android:name=".InCassReceiver"2 android:enable="treu">3 <intent-=filter>4 <action android:name="android.intent.action.PHONE_STATE"/>5 <intent-filter>6 </recevier>
來電資訊的攔截以及判斷