Android中自动拦截电话

1.AndroidMainFest.xml文件设置

需要的权限

<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
注册服务:
<service android:name=".MyService"/>
2.添加AIDL文件(a、包名:com.android.internal.telephony的ITelephony类 b、包名:android.telephony的NeighboringCellInfo类	
NeighboringCellInfo类里边的内容(
package android.telephony;
parcelable NeighboringCellInfo;
3.public class MyService extends Service {
 
  
//系统提供的电话管理器
private TelephonyManager telephonyManager;
private MyPhoneListener myPhoneListener;
@Override
public IBinder onBind(Intent intent) {return null;}
@Override
public void onCreate() {
    telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    myPhoneListener = new MyPhoneListener();
    telephonyManager.listen(myPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
    super.onCreate();
}
private class MyPhoneListener extends PhoneStateListener{
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        super.onCallStateChanged(state, incomingNumber);

        switch (state){
            case TelephonyManager.CALL_STATE_IDLE:
                break;
            case TelephonyManager.CALL_STATE_RINGING:
                endCall();
                Toast.makeText(getApplication(),"挂了!",Toast.LENGTH_SHORT).show();
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                break;
        }
    }
}
private void endCall(){
    try {
        Class aClass = getClassLoader().loadClass("android.os.ServiceManager");
       Method method = aClass.getDeclaredMethod("getService",String.class);
       IBinder iBinder = (IBinder) method.invoke(null,TELEPHONY_SERVICE);
	在使用ITelephony类之前先clean一下项目,不然可能找不到
        ITelephony iTelephony = ITelephony.Stub.asInterface(iBinder);
        iTelephony.endCall();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
@Override
public void onDestroy() {
    telephonyManager.listen(myPhoneListener, PhoneStateListener.LISTEN_NONE);
    myPhoneListener = null;
    super.onDestroy();
}
4. MainActivity
private Intent  callSmsSafeIntent;
在onCreate方法中{
callSmsSafeIntent = new Intent(this,MyService.class);
//开启拦截服务
startService(callSmsSafeIntent);
}

你可能感兴趣的:(Android,Studio)