exPhoneCallListener myPhoneCallListener = new exPhoneCallListener();
/* 取得电话服务 */
TelephonyManager tm = (TelephonyManager) this.getSystemService
(Context.TELEPHONY_SERVICE);
/* 注册Listener */
tm.listen(myPhoneCallListener, PhoneStateListener.LISTEN_CALL_STATE);
/* 内部class继承PhoneStateListener */
public class exPhoneCallListener extends PhoneStateListener
{
//重写onCallStateChanged当状态改变时
public void onCallStateChanged(int state, String incomingNumber)
{switch (state){
case TelephonyManager.CALL_STATE_IDLE: //空闲状态
myTextView1.setText("CALL_STATE_IDLE");
break;
case TelephonyManager.CALL_STATE_OFFHOOK: //接起电话时
myTextView1.setText("CALL_STATE_OFFHOOK");
break;
case TelephonyManager.CALL_STATE_RINGING: //电话进来时
myTextView1.setText("CALL_STATE_RINGING");
if ("333333".equals(incomingNumber)) //电话333333时挂断
{ try
{iTelephony.endCall();}
catch (RemoteException e)
{ e.printStackTrace();}
}
break;
default:
break;
}
super.onCallStateChanged(state, incomingNumber);
}
对于挂断电话,本来是一个很好实现的功能。可惜Android新发布的版本中没有提供简
便的挂断 API, 这些API被隐藏了,程序不能直接使用。想要调用Android中隐藏的API 有
两种方法,一种是在编译后的源码中提取该隐藏类所在的 jar 包,然后导入项目中调用;二
是从编译前的源码中提取相应的 java 类,将其包含在项目中使用。我们通过以下方法来实
现:
1. 在 src 下新建一个包:com.android.internal.telephony(和 ITelephony.aidl 中
package 声明的包名一样);
2. 然后把从系统源码中把ITelephony.aidl文件拷贝到com.android.internal.telephony
包下。也可以先新建一个ITelephony.aidl, 然后再把内容拷贝进去(ITelephony.aidl
文件内容可以在互连网上获取,这个方法适合没有SDK源码文件的开发者);
3. 在src下新建一个包:android.telephony, 然后新建一个NeighboringCellInfo.aidl,
其内容为:
package android.telephony;
parcelable NeighboringCellInfo;
4.从私有方法中获取ITelephony: 代码如下。
tManager = (TelephonyManager)
this.getSystemService(Context.TELEPHONY_SERVICE);
//初始化 iTelephony
Class<TelephonyManager> c = TelephonyManager.class;
Method getITelephonyMethod = null;
try {
getITelephonyMethod = c.getDeclaredMethod("getITelephony",
(Class[])null);
getITelephonyMethod.setAccessible(true);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
iTelephony = (ITelephony) getITelephonyMethod.invoke(tManager,
(Object[])null);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
最后挂断只需调用iTelephony的 endcall()函数即可。
至此程序关键代码已经编写完毕,一个Android下的简单来电防火墙程序的框架就实现
了。现在我们在 Android模拟器中运行该程序以检验实际效果。在Eclipse中选中项目,点
击右键后选择Run as > Android Application。稍作等待就会出现Android模拟器的界面。
等待模拟器启动完成后我们可以看到程序界面,说明程序已经运行起来了。下面要做的事就 |