新建一个名为ITelephony的aidl文件,注意包名不能改变,因为是通过反射方式来实现接听和挂断的
ITelephony.aidl
package com.android.internal.telephony;
interface ITelephony{
boolean endCall();
void answerRingingCall();
}
public class CallManager {
private static CallManager instance = null;
private static final String MANUFACTURER_HTC = "HTC";
public static synchronized CallManager getInstance() {
if (instance == null) {
instance = new CallManager();
}
return instance;
}
/** 接听电话*/
public void acceptCall(Context context) {
try {
Method method = Class.forName("android.os.ServiceManager")
.getMethod("getService", String.class);
IBinder binder = (IBinder) method.invoke(null, new Object[]{Context.TELEPHONY_SERVICE});
ITelephony telephony = ITelephony.Stub.asInterface(binder);
telephony.answerRingingCall();
} catch (Exception e) {
Log.e(TAG, "for version 4.1 or larger");
acceptCall_4_1(context);
}
}
/**4.1版本以上接听电话*/
public void acceptCall_4_1(Context context) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
;
//模拟无线耳机的按键来接听电话
// for HTC devices we need to broadcast a connected headset
boolean broadcastConnected = MANUFACTURER_HTC.equalsIgnoreCase(Build.MANUFACTURER)
&& !audioManager.isWiredHeadsetOn();
if (broadcastConnected) {
broadcastHeadsetConnected(context, false);
}
try {
try {
Runtime.getRuntime().exec("input keyevent " +
Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK));
} catch (IOException e) {
// Runtime.exec(String) had an I/O problem, try to fall back
String enforcedPerm = "android.permission.CALL_PRIVILEGED";
Intent btnDown = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(
Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_HEADSETHOOK));
Intent btnUp = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(
Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_HEADSETHOOK));
context.sendOrderedBroadcast(btnDown, enforcedPerm);
context.sendOrderedBroadcast(btnUp, enforcedPerm);
}
} finally {
if (broadcastConnected) {
broadcastHeadsetConnected(context, false);
}
}
}
private void broadcastHeadsetConnected(Context context, boolean connected) {
Intent i = new Intent(Intent.ACTION_HEADSET_PLUG);
i.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
i.putExtra("state", connected ? 1 : 0);
i.putExtra("name", "mysms");
try {
context.sendOrderedBroadcast(i, null);
} catch (Exception e) {
}
}
/** 拒绝接听*/
public void rejectCall() {
try {
Method method = Class.forName("android.os.ServiceManager")
.getMethod("getService", String.class);
IBinder binder = (IBinder) method.invoke(null, new Object[]{Context.TELEPHONY_SERVICE});
ITelephony telephony = ITelephony.Stub.asInterface(binder);
telephony.endCall();
} catch (NoSuchMethodException e) {
Log.d(TAG, "", e);
} catch (ClassNotFoundException e) {
Log.d(TAG, "", e);
} catch (Exception e) {
}
}
}