Android------------------系統服務呼叫的學習
一、ServiceManager的方法: 此方法getService,用於根據名稱獲取當前的IBinder的代理(並沒有直接獲取服務),
服務提供的功能是依靠IBinder間接呼叫的(返回值IBinder)
// 在真機的環境中是有此類: android.os.ServiceManager 因此我們可以採用Java反射機制來獲取
Class clazz = Class.forName("android.os.ServiceManager");
Method method = clazz.getMethod("getService", String.class);
// 系統註冊的服務都可以在Context中檢視
IBinder iBinder = (IBinder) method.invoke(null,
Context.TELEPHONY_SERVICE);
// 獲取系統提供的ITelephony服務
//它binderService哪個服務,通過serviceConnect就可以回傳得到,telephony就會得到回傳的那個服務
ITelephony telephony = (ITelephony) ITelephony.Stub.asInterface(iBinder);
二、Content.getSystemService : 是用來獲取服務管理器(不是服務),對服務的監聽,符合事件的處理
都要通過服務管理器完成的,系統預設管理器(返回相應的服務管理器的物件)
// TelephonyManager:是Telephony服務的管理類.
tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
三、打電話經常用到的兩個檔案
1.TelephoneManager : 是Telephony服務的管理類.
2.PhoneStateListener : 手機監聽狀態
電話的大致流程:
//獲得當前的Telephony服務的管理類
tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
//啟動對Telephony的監聽
tm.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
private PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
// 當手機電話的狀態發生變化,則此方法會呼叫
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.i("jxy", "空閒.........");
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.i("jxy", "響鈴.........");
if (incomingNumber.equals("110")) {
endCall();
}
break;
default:
Log.i("jxy", "接通.........");
break;
}
}
};
四、呼叫系統服務的一些注意事項
1.不能在Activity中去註冊系統服務,這樣下次啟動服務的時候會重複註冊。
應該用我們自己的服務去呼叫系統的服務,應該使用startService,不能使用
binderService。因為使用binderService,Activity銷燬的時候就會解綁,通話就會斷開