您的位置:首页 > 移动开发 > Android开发

Android开发之来电电话挂断实现

2014-11-30 19:04 253 查看
在Android1.5版本之前,实现挂断电话是非常容易的事,只需要调用TelephonyManager的endCall()方法就可以了,但在1.5版本之后,Google工程师为了手机的安全期间,把endCall的方法隐藏掉了。所以实现挂断电话可以通过反射的方法,执行endCall方法。具体实现如下:

TelephonyManager在源码里是这样描述的:Context.getSystemService(Context.TELEPHONY_SERVICE)},我们通过TELEPHONY_SERVICE系统服务调用就可以获取。

registerService(TELEPHONY_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new TelephonyManager(ctx.getOuterContext());
                }});


而 android.os.ServiceManager 有getService方法

/**
     * Returns a reference to a service with the given name.
     *
     * @param name the name of the service to get
     * @return a reference to the service, or <code>null</code> if the service doesn't exist
     */
    public static IBinder getService(String name) {
        return null;
    }


android.telephony.TelephonyManager 类是代理ITelephony接口的,可以看到里面的endCall是被隐藏掉的。

/**
 * Interface used to interact with the phone.  Mostly this is used by the
 * TelephonyManager class.  A few places are still using this directly.
 * Please clean them up if possible and use TelephonyManager insteadl.
 *
 * {@hide}
 */
interface ITelephony {

    /**
     * Dial a number. This doesn't place the call. It displays
     * the Dialer screen.
     * @param number the number to be dialed. If null, this
     * would display the Dialer screen with no number pre-filled.
     */

/**
     * End call or go to the Home screen
     *
     * @return whether it hung up
     */
    boolean endCall();


我们知道利用绑定服务可以调用里面的方法,会返回一个IBinder对象,利用IBinder可以调用服务里的方法。

TelephonyManager实际上就是系统电话服务的代理对象,通过aidl获取IBinder,然后进一步的进行封装。代理有限的方法。

TelephonyManager ------------------IBinder-------------------------系统服务

代理对象 aidl

所以实现需要一下步奏:

1 、 反射加载ServiceManager类。

2、 获取IBinder对象执行getService方法。

3、 在项目中新建com.android.internal.telephony包(包名不能变),然后拷贝ITelephony.aidl。 在新建android.telephony包,拷贝NeighboringCellInfo.aidl 的进程通信接口两个文件。

4、调用endCall方法。

实现方法如下:

private void endCall() {
			// IBinder iBinder = ServiceManager.getService(TELEPHONY_SERVICE);
			// ServiceManager 是被系统隐藏掉了 所以只能用反射的方法获取
			try {
				// 加载ServiceManager的字节码
				Class<?> clazz = CallSMSSafeService.class.getClassLoader()
						.loadClass("android.os.ServiceManager");
				Method method = clazz.getDeclaredMethod("getService",
						String.class);
				IBinder iBinder = (IBinder) method.invoke(null,
						TELEPHONY_SERVICE);
				ITelephony.Stub.asInterface(iBinder).endCall();
			} catch (Exception e) {
				e.printStackTrace();
				Log.i(TAG, "拦截电话异常");
			}

		}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: