如何拦截来电,并检测到某些特定号码时自动挂断电话?写出关键代码。
拦截来电只需要编写一个广播接收类即可,但用代码挂断电话从Android SDK
1.5开始就将这个功能隐藏了,因此无法通过常规的方法挂断电话。不过可以通过反射技术访问Android SDK的内部功能来挂断电话。
拦截来电的广播接收类(InCallReceiver)的onReceiver方法的代码如下:
public void onReceive(final Context context, Intent intent)
{
//获得电话管理服务,以便获得电话的状态
TelephonyManager tm=(TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
//根据不同的来电状态进行处理
switch(tm.getCallState())
{
case TelephonyManager.CALL_STATE_RINGING://响铃
//获得来电的号码
String incomingNumber=intent.getStringExtra("incoming_number");
//如果来电号码是12345678,则挂断电话
if("12345678".equals(incomingNumber))
{
Class<TelephonyManager> telephonyManagerClass=TelephonyManager.class;
//通过Java反射技术获取getITelephony方法对应的Method对象
Method telephonyMethod=telephonyManagerClass.getDeclaredMethod("getITelephony",(Class[]) null);
//允许访问getITelephony方法
telephonyMethod.setAccessible(true);
//调用getITelephony方法获取ITelephony对象
Object obj=telephonyMethod.invoke(telephonyManager,(Object[])null);
//获取与endCall方法对应的Method对象
Method endCallMethod=obj.getClass().getMethod("endCall",null);
//允许访问endCall方法
endCallMethod.setAccessible(true);
//调用endCall方法挂断电话
endCallMethod.invoke(obj,null);
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK;//接听电话
Log.d("call_state","offhook");
break;
case TelephonyManager.CALL_STATE_IDLE://挂断电话
closeToast();
}
}
如何拦截来电,并检测到某些特定号码时自动挂断电话,布布扣,bubuko.com
原文:http://www.cnblogs.com/dazuihou/p/3587316.html