最近了解了一下电话拦截,写了一下demo。在这里给大家分享一下吧!我写的是去电自动挂断。通过隐私启动来拨打电话,由于使用常规方法无法挂断电话,所以需使用反射技术实现通过程序挂断电话。虽然这种方法并没有直接调用服务,但却使用了AIDL文件自动生成的接口。接口名为Itelephony.(AIDL是安卓接口定义语言的缩写)。官方提供了aidl文件,只需把NeighboringCellInfo.aid和Itelephony这两个放到对应的包中就行了。代码如下:
package com.example.an_service2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.android.internal.telephony.ITelephony;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by Administrator on 2017/2/13.
*/
public class Rervice extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.PHONE_STATE".equals(intent.getAction())) {
//先得到电话管理者
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//得到电话的状态
int phonrstate = telephonyManager.getCallState();
switch (phonrstate) {
case TelephonyManager.CALL_STATE_RINGING:
//得到号码:
String number = intent.getStringExtra("incoming_number");
Log.i("Test", "电话来了" + number);
//得到电话管理者类对象
Class<TelephonyManager> clazz = TelephonyManager.class;
//方法
try {
Method method = clazz.getDeclaredMethod("getITelephony", null);
// 允许访问私有方法
method.setAccessible(true);
// 执行方法
ITelephony iTelephony= (ITelephony) method.invoke(telephonyManager,null);
// 判断
if("18684662845".equals(number)){
iTelephony.endCall();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.i("test","通话中。。。");
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.i("test","挂断");
break;
}
}
}
}
Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.an_service2">
<!--电话状态权限-->
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<!--打电话权限-->
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".Rervice">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"></action>
</intent-filter>
</receiver>
</application>
</manifest>