編輯:關於 Android 程式設計
本文以 Android 4.0 為基礎,逐層追蹤一通來電從 Modem 到使用者界面的完整旅程,幫助讀者理解電話模組各層之間如何協作。
開機時系統會自動啟動 PhoneApp 類別,這得益於 AndroidManifest.xml 中的設定。由於 Phone.apk 安裝於 /system/app/ 目錄,並配置了 android:persistent="true" 屬性,因此開機即被拉起。PhoneApp 初始化時會進入 onCreate 回呼:
@Override
public void onCreate() {
//.......
if (phone == null) {
//........
// 建立 CallNotifier 單例,負責處理來自電話層的非同步事件,
// 例如來電時啟動來電 UI。
notifier = CallNotifier.init(this, phone, ringer, mBtHandsfree, new CallLogAsync());
//........
}
}
此處對 CallNotifier 進行初始化,而 CallNotifier 的核心職責正是監聽電話狀態。
在 CallNotifier 的建構子中,會呼叫 registerForNotifications(),向 Framework 層的 CallManager 註冊一系列通知:
private CallNotifier(PhoneApp app, Phone phone, Ringer ringer, BluetoothHandsfree btMgr, CallLogAsync callLog) {
//............
// 與 CallManager 註冊通知,與 Framework 溝通
registerForNotifications();
//...............
}
private void registerForNotifications() {
mCM.registerForNewRingingConnection(this, PHONE_NEW_RINGING_CONNECTION, null);
mCM.registerForPreciseCallStateChanged(this, PHONE_STATE_CHANGED, null);
mCM.registerForDisconnect(this, PHONE_DISCONNECT, null);
mCM.registerForUnknownConnection(this, PHONE_UNKNOWN_CONNECTION_APPEARED, null);
mCM.registerForIncomingRing(this, PHONE_INCOMING_RING, null);
// ……其餘註冊省略
}
其中 registerForNewRingingConnection 正是用來監聽來電的關鍵。在 CallManager.java 中,其本質是把 handler 加入一個登記清單:
public void registerForPreciseCallStateChanged(Handler h, int what, Object obj) {
mPreciseCallStateRegistrants.addUnique(h, what, obj);
}
當訊息抵達時,CallNotifier 的 handleMessage 會分派處理:
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case PHONE_NEW_RINGING_CONNECTION:
log("RINGING... (new)");
onNewRingingConnection((AsyncResult) msg.obj);
mSilentRingerRequested = false;
break;
//...........
}
}
當 Modem(調變解調器)收到來電資訊,會透過 AT 指令把資料送給 RILC,再由 RILC 透過 socket 傳給 RILJ,逐層向上傳遞至 Framework,最終顯示來電響鈴界面。這一切的起點,是 RIL 中的內部類別 RILReceiver:
class RILReceiver implements Runnable {
byte[] buffer;
RILReceiver() {
buffer = new byte[RIL_MAX_COMMAND_BYTES];
}
public void run() {
int retryCount = 0;
try {
for (;;) {
LocalSocket s = null;
LocalSocketAddress l;
try {
s = new LocalSocket();
l = new LocalSocketAddress(SOCKET_NAME_RIL, LocalSocketAddress.Namespace.RESERVED);
s.connect(l);
} catch (IOException ex) {
// 連線失敗時的重試邏輯省略
retryCount++;
continue;
}
retryCount = 0;
mSocket = s;
// 讀取並處理資料
InputStream is = mSocket.getInputStream();
for (;;) {
Parcel p;
length = readRilMessage(is, buffer);
if (length < 0) break;
p = Parcel.obtain();
p.unmarshall(buffer, 0, length);
p.setDataPosition(0);
processResponse(p);
p.recycle();
}
}
} catch (Throwable tr) {
Log.e(LOG_TAG, "Uncaught exception", tr);
}
notifyRegistrantsRilConnectionChanged(-1);
}
}
在 RIL 的建構子中會建立 RILReceiver 並啟動其執行緒:
public RIL(Context context, int preferredNetworkType, int cdmaSubscription) {
//..................
mReceiver = new RILReceiver();
mReceiverThread = new Thread(mReceiver, "RILReceiver");
mReceiverThread.start();
//.................
}
由於 RIL 在 PhoneApp 中即完成初始化,RILReceiver 作為一個使用 Socket 通訊的執行緒,會在讀到資料後呼叫 processResponse:
private void processResponse(Parcel p) {
int type;
type = p.readInt();
if (type == RESPONSE_UNSOLICITED) {
processUnsolicited(p); // 主動響應
} else if (type == RESPONSE_SOLICITED) {
processSolicited(p); // 響應請求
}
releaseWakeLockIfDone();
}
來電走的正是主動響應分支:
private void processUnsolicited(Parcel p) {
//..............
case RIL_UNSOL_CALL_RING:
ret = responseCallRing(p);
break;
//..............
case RIL_UNSOL_CALL_RING:
if (mRingRegistrant != null) {
mRingRegistrant.notifyRegistrant(new AsyncResult(null, ret, null));
}
break;
//..............
}
接著進入 Registrant 類別,透過 notifyRegistrant 把結果封裝成 Message 發送出去:
public void notifyRegistrant(AsyncResult ar) {
internalNotifyRegistrant(ar.result, ar.exception);
}
/*package*/ void internalNotifyRegistrant(Object result, Throwable exception) {
Handler h = getHandler();
if (h == null) {
clear();
} else {
Message msg = Message.obtain();
msg.what = what;
msg.obj = new AsyncResult(userObj, result, exception);
h.sendMessage(msg);
}
}
當 PhoneApp 收到 PHONE_NEW_RINGING_CONNECTION,會進入 onNewRingingConnection。這個方法會先排除一些應直接忽略的來電情境(例如全部拒接),再檢查連線狀態,取得部分 WakeLock 避免 CPU 休眠,最後依是否為真正的來電決定播放鈴聲或來電等待提示音,並呼叫 showIncomingCall():
private void showIncomingCall() {
log("showIncomingCall()... phone state = " + mCM.getState());
try {
ActivityManagerNative.getDefault().closeSystemDialogs("call");
} catch (RemoteException e) { }
mApplication.preventScreenOn(true);
mApplication.requestWakeState(PhoneApp.WakeState.FULL);
// 發布來電通知,並帶上啟動來電 UI 的 fullScreenIntent
mApplication.notificationMgr.updateNotificationAndLaunchIncomingCallUi();
}
NotificationMgr 會設定高優先級通知並掛上 fullScreenIntent:
public void updateNotificationAndLaunchIncomingCallUi() {
// allowFullScreenIntent=true 表示必要時應啟動來電 UI
updateInCallNotification(true);
}
而啟動 UI 的關鍵在於 PendingIntent:
PendingIntent inCallPendingIntent =
PendingIntent.getActivity(mContext, 0, PhoneApp.createInCallIntent(), 0);
notification.contentIntent = inCallPendingIntent;
static Intent createInCallIntent() {
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
intent.setClassName("com.android.phone", getCallScreenClassName());
return intent;
}
static String getCallScreenClassName() {
return InCallScreen.class.getName();
}
透過這個 PendingIntent,系統便啟動 InCallScreen 來電界面,使用者接聽後的體驗就跟撥號界面別無二致。
在驗證 android:persistent="true" 時可以發現,只有安裝在 /system/app/ 目錄下的程式才會在開機時啟動,且啟動後不會被系統回收。開機後 logcat 便能看到程式在 onCreate 中印出的訊息,這也解釋了為何電話等核心應用具備如此高的存活能力。
Android 懸浮窗菜單的實作教學
Android 懸浮窗菜單的實作教學 本文分享一個以 Service 為基礎實作的懸浮窗菜單,透過 FloatMenuManager 單例管理生命週期,並示範如何隱藏狀態
Android 百度地圖自訂彈出視窗的實作方式
需求背景 使用百度地圖時,點擊 Marker 通常會出現預設資訊窗。若希望顯示自訂內容、加入按鈕或呈現自己的資料模型,預設的 PopupOverlay 往往不夠靈活,因為
Android Service 生命週期與 bindService 呼叫服務方法詳解
服務的生命週期 服務的生命週期與啟動服務的方法有關。 當採用 Context.startService() 啟動服務,相關的生命週期方法為: onCreate() → o
Android Binder 機制在應用程式框架層的 Java 介面原始碼解析
Java 層如何使用 Binder Android 系統的 Binder 機制底層多以 C 或 C++ 實作,但應用程式開發主要使用 Java。為了讓 Java 應用程式