Android開發(fā)之來(lái)電電話掛斷實(shí)現(xiàn)
掃描二維碼
隨時(shí)隨地手機(jī)看文章
在Android1.5版本之前,實(shí)現(xiàn)掛斷電話是非常容易的事,只需要調(diào)用TelephonyManager的endCall()方法就可以了,但在1.5版本之后,Google工程師為了手機(jī)的安全期間,把endCall的方法隱藏掉了。所以實(shí)現(xiàn)掛斷電話可以通過(guò)反射的方法,執(zhí)行endCall方法。具體實(shí)現(xiàn)如下:
TelephonyManager在源碼里是這樣描述的:Context.getSystemService(Context.TELEPHONY_SERVICE)},我們通過(guò)TELEPHONY_SERVICE系統(tǒng)服務(wù)調(diào)用就可以獲取。
?
1
2
3
4
|
registerService(TELEPHONY_SERVICE, new ServiceFetcher() { public Object createService(ContextImpl ctx) { return new TelephonyManager(ctx.getOuterContext()); }}); |
而 android.os.ServiceManager 有g(shù)etService方法
?
1
2
3
4
5
6
7
8
9
|
/** * 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是被隱藏掉的。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
/** * 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(); |
我們知道利用綁定服務(wù)可以調(diào)用里面的方法,會(huì)返回一個(gè)IBinder對(duì)象,利用IBinder可以調(diào)用服務(wù)里的方法。
TelephonyManager實(shí)際上就是系統(tǒng)電話服務(wù)的代理對(duì)象,通過(guò)aidl獲取IBinder,然后進(jìn)一步的進(jìn)行封裝。代理有限的方法。
TelephonyManager ------------------IBinder-------------------------系統(tǒng)服務(wù)
代理對(duì)象 aidl
所以實(shí)現(xiàn)需要一下步奏:
1 、 反射加載ServiceManager類。
2、 獲取IBinder對(duì)象執(zhí)行g(shù)etService方法。
3、 在項(xiàng)目中新建com.android.internal.telephony包(包名不能變),然后拷貝ITelephony.aidl。 在新建android.telephony包,拷貝NeighboringCellInfo.aidl 的進(jìn)程通信接口兩個(gè)文件。
4、調(diào)用endCall方法。
實(shí)現(xiàn)方法如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
private void endCall() { // IBinder iBinder = ServiceManager.getService(TELEPHONY_SERVICE); // ServiceManager 是被系統(tǒng)隱藏掉了 所以只能用反射的方法獲取 try { // 加載ServiceManager的字節(jié)碼 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, "攔截電話異常" ); } } |