1、通过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;
}
}
};
aidl下载地址:http://download.csdn.net/detail/ab6326795/7993671
2、通过广播通知系统进行接听和挂断
由于Android2.3以上添加了对permissionandroid.permission.MODIFY_PHONE_STATE的限制,2.3之前的通过反射机制调用ITelephone的能力的做法已经不适用。
2.3上实现方式:
public synchronized void answerRingingCall() {
查询系统PhoneAPP应用(PhoneGlobals.java)实现了对耳机插入、多媒体按键等通知的接受和处理。当中未发现有特殊的地方。个人觉得。假设系统接收到此广播应该能够进行接听或挂断操作。
// 2.3以上运行下面代码实现自己主动接听 Intent mintent = new Intent(Intent.ACTION_MEDIA_BUTTON); //按下音量 KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK); mintent.putExtra("android.intent.extra.KEY_EVENT", keyEvent); // 通话权限 同意程序拨打电话, 替换系统的拨号器界面 mContext.sendOrderedBroadcast(mintent,"android.permission.CALL_PRIVILEGED"); mintent = new Intent(Intent.ACTION_MEDIA_BUTTON); keyEvent = new KeyEvent(KeyEvent.ACTION_UP,KeyEvent.KEYCODE_HEADSETHOOK); mintent.putExtra("android.intent.extra.KEY_EVENT", keyEvent); mContext.sendOrderedBroadcast(mintent,"android.permission.CALL_PRIVILEGED");
两个都须要权限
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" /> <!-- 拨打电话的权限 --> <uses-permission android:name="android.permission.CALL_PHONE"/>
综合两种方法就能够做出电话自己主动接听和挂断的APP了