天天看點

Android studio 上代碼實作來電攔截

第一步:在程式中建立一個包,包名必須為:com.android.internal.telephony,因為要使用aidl。 a. aidl檔案放在aidl目錄下, 和java目錄同級

Android studio 上代碼實作來電攔截
Android studio 上代碼實作來電攔截
Android studio 上代碼實作來電攔截

b. ITelephony.aidl檔案的包名是com.android.internal.telephony;

Android studio 上代碼實作來電攔截

第二步:在這個包裡面建立一個名為ITelephony.aidl的檔案,然後在檔案裡面寫入代碼: [java]   view plain   copy

  1. package com.android.internal.telephony;  
  2.     interface ITelephony{  
  3.         boolean endCall();  
  4.         void answerRingingCall();  
  5.     }  

第三步:在AndroidManifest.xml中加入權限

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

第四步:如果ITelephony識别不到,需要"Make Project"

Android studio 上代碼實作來電攔截

第五步:檢測來電 //引入包 import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import com.android.internal.telephony.ITelephony;

//定義 TelephonyManager telephonyManager;

//onCreate執行 MyPhoneStateListener phoneListener=new MyPhoneStateListener(); //我們派生的類 telephonyManager =(TelephonyManager)getSystemService(TELEPHONY_SERVICE); telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);

//來電号碼識别和攔截 public class MyPhoneStateListener extends PhoneStateListener { Context context; @Override public void onCallStateChanged(int state, String incomingNumber) { switch (telephonyManager.getCallState()) { case TelephonyManager.CALL_STATE_RINGING: System.out.println("###### Incoming number=" + incomingNumber);//incomingNumber就是來電号碼 endCall(); break; case TelephonyManager.CALL_STATE_OFFHOOK: break; case TelephonyManager.CALL_STATE_IDLE: break; } } }

private void endCall() { Class<TelephonyManager> c = TelephonyManager.class; try { Method getITelephonyMethod = c.getDeclaredMethod("getITelephony", (Class[]) null); getITelephonyMethod.setAccessible(true);

ITelephony iTelephony = null; System.out.println("###### End call."); iTelephony = (ITelephony) getITelephonyMethod.invoke(telephonyManager, (Object[]) null); iTelephony.endCall(); } catch (Exception e){ System.out.println("###### Fail to answer ring call."); e.printStackTrace(); } }

繼續閱讀