---
title: "Android实现来电自动挂断实现机制"
author: "cqfly"
date: "2011-04-01T23:36:07Z"
tags: []
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2011-04-01T23:37:24Z"
id: 983617
url: "https://cqfly.iteye.com/blog/983617"
---

通过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&lt;TelephonyManager&gt; 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;  
            }  
        }

    };

 

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

 

&lt;uses-permission android:name="android.permission.CALL\_PHONE"/&gt;  
&lt;uses-permission android:name="android.permission.READ\_PHONE\_STATE"/&gt;