当前位置: 代码迷 >> Android >> Android兑现来电自动挂断实现机制
  详细解决方案

Android兑现来电自动挂断实现机制

热度:71   发布时间:2016-05-01 16:42:53.0
Android实现来电自动挂断实现机制

通过aidl及反射实现挂断电话
具体分三步:
(1)ITelephony.aidl ,必须新建com.android.internal.telephony包并放入ITelephony.aidl文件(构建后在gen下有ITelephony.java文件,这是aidl生成的接口),文件内容如下:
package com.android.internal.telephony;
interface ITelephony{
??? boolean endCall();
??? void answerRingingCall();
}
(2)在需要的类中添加如下方法,代码如下(通过反射获取电话接口的实例)

/**
??? ?* @param context
??? ?* @return
??? ?*/
??? private static ITelephony getITelephony(Context context) {
??? ??? TelephonyManager mTelephonyManager = (TelephonyManager) context
??? ??? ??? ??? .getSystemService(TELEPHONY_SERVICE);
??? ??? Class<TelephonyManager> c = TelephonyManager.class;
??? ??? Method getITelephonyMethod = null;
??? ??? try {
??? ??? ??? getITelephonyMethod = c.getDeclaredMethod("getITelephony",
??? ??? ??? ??? ??? (Class[]) null); // 获取声明的方法
??? ??? ??? getITelephonyMethod.setAccessible(true);
??? ??? } catch (SecurityException e) {
??? ??? ??? e.printStackTrace();
??? ??? } catch (NoSuchMethodException e) {
??? ??? ??? e.printStackTrace();
??? ??? }

??? ??? try {
??? ??? ??? ITelephony iTelephony = (ITelephony) getITelephonyMethod.invoke(
??? ??? ??? ??? ??? mTelephonyManager, (Object[]) null); // 获取实例
??? ??? ??? return iTelephony;
??? ??? } catch (Exception e) {
??? ??? ??? e.printStackTrace();
??? ??? }
??? ??? return iTelephony;
??? }

(3)在来电时调用此实例,然后调用此endCall()方法。

mTelephonyManager = (TelephonyManager) this
??? ??? ??? ??? .getSystemService(TELEPHONY_SERVICE);
??? ??? mTelephonyManager.listen(phoneStateListener,
??? ??? ??? ??? PhoneStateListener.LISTEN_CALL_STATE);

//电话实例
PhoneStateListener phoneStateListener = new PhoneStateListener() {

??? ??? @Override
??? ??? public void onCallStateChanged(int state, String incomingNumber) {

??? ??? ??? switch (state) {
??? ??? ??? ??? case TelephonyManager.CALL_STATE_RINGING :
??? ??? ??? ??? ??? iTelephony = getITelephony(getApplicationContext()); //获取电话接口
??? ??? ??? ??? ??? if (iTelephony != null) {
??? ??? ??? ??? ??? ??? try {
??? ??? ??? ??? ??? ??? ??? iTelephony.endCall(); // 挂断电话
??? ??? ??? ??? ??? ??? ??? Toast.makeText(getApplicationContext(),
??? ??? ??? ??? ??? ??? ??? ??? ??? "endCall "+ incomingNumber +"? successful!", 3000).show();
??? ??? ??? ??? ??? ??? } catch (RemoteException e) {
??? ??? ??? ??? ??? ??? ??? e.printStackTrace();
??? ??? ??? ??? ??? ??? }
??? ??? ??? ??? ??? }
??? ??? ??? ??? ??? break;
??? ??? ??? ??? default :
??? ??? ??? ??? ??? break;
??? ??? ??? }
??? ??? }

??? };

?

//注意:在功能清单文件中添加电话的权限:

?

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

  相关解决方案