Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 4.0 撥號啟動流程剖析(三):PhoneApp 與 Framework 層的通訊

編輯:關於 Android 程式設計

Android 幾乎所有原始碼都公開,要分析 Framework 就先把碼拿到手。我在 Ubuntu 14.04 上搭好環境並下載 Android 4.0 原始碼(含 Framework 與 Package),掛到 Windows 上用 Source Insight 3.5 閱讀;Package 部分則匯入 Eclipse 看。實務上不必匯入整個 frameworks/base——像 media/tests/contents/media_api 塞滿影音資源,匯進去只會拖慢索引。建議只挑 core、telephony、services、include 這幾個目錄。

一、從 PhoneApp 的初始化說起

PhoneApp 啟動時的關鍵片段:

@Override
public void onCreate() {
    // ...
    if (phone == null) {
        // 初始化 framework 層的 phone
        PhoneFactory.makeDefaultPhones(this);

        // 取得預設 phone 物件
        phone = PhoneFactory.getDefaultPhone();
        mCM = CallManager.getInstance();
        mCM.registerPhone(phone);
        // ...
    }
    // ...
}

應用層只呼叫了 PhoneFactory 的靜態方法,真正的重活在 framework 裡,而 framework 採用了代理模式 + 工廠模式的組合。

二、PhoneFactory.makeDefaultPhone 做了什麼

public static void makeDefaultPhones(Context context) {
    makeDefaultPhone(context);
}

public static void makeDefaultPhone(Context context) {
    synchronized (Phone.class) {
        if (sMadeDefaults) return;

        sLooper = Looper.myLooper();
        sContext = context;
        if (sLooper == null) {
            throw new RuntimeException("PhoneFactory.makeDefaultPhone must be called from Looper thread");
        }

        // 用 UNIX domain socket 避免重複初始化
        int retryCount = 0;
        for (;;) {
            boolean hasException = false;
            retryCount++;
            try {
                new LocalServerSocket("com.android.internal.telephony");
            } catch (java.io.IOException ex) {
                hasException = true;
            }
            if (!hasException) break;
            if (retryCount > SOCKET_OPEN_MAX_RETRY) {
                throw new RuntimeException("PhoneFactory probably already running");
            }
            try {
                Thread.sleep(SOCKET_OPEN_RETRY_MILLIS);
            } catch (InterruptedException er) { }
        }

        sPhoneNotifier = new DefaultPhoneNotifier();

        // 決定偏好的網路模式
        int preferredNetworkMode = RILConstants.PREFERRED_NETWORK_MODE;
        if (BaseCommands.getLteOnCdmaModeStatic() == Phone.LTE_ON_CDMA_TRUE) {
            preferredNetworkMode = Phone.NT_MODE_GLOBAL;
        }
        int networkMode = Settings.Secure.getInt(context.getContentResolver(),
                Settings.Secure.PREFERRED_NETWORK_MODE, preferredNetworkMode);

        // 決定 CDMA 訂閱來源
        int cdmaSubscription;
        switch (BaseCommands.getLteOnCdmaModeStatic()) {
            case Phone.LTE_ON_CDMA_FALSE:
                cdmaSubscription = RILConstants.SUBSCRIPTION_FROM_NV;
                break;
            case Phone.LTE_ON_CDMA_TRUE:
                cdmaSubscription = RILConstants.SUBSCRIPTION_FROM_RUIM;
                break;
            default:
                cdmaSubscription = Settings.Secure.getInt(context.getContentResolver(),
                        Settings.Secure.PREFERRED_CDMA_SUBSCRIPTION, preferredCdmaSubscription);
                break;
        }

        // 建立命令介面(讀系統屬性後決定行為)
        sCommandsInterface = new RIL(context, networkMode, cdmaSubscription);

        int phoneType = getPhoneType(networkMode);
        if (phoneType == Phone.PHONE_TYPE_GSM) {
            sProxyPhone = new PhoneProxy(new GSMPhone(context, sCommandsInterface, sPhoneNotifier));
        } else if (phoneType == Phone.PHONE_TYPE_CDMA) {
            switch (BaseCommands.getLteOnCdmaModeStatic()) {
                case Phone.LTE_ON_CDMA_TRUE:
                    sProxyPhone = new PhoneProxy(new CDMALTEPhone(context, sCommandsInterface, sPhoneNotifier));
                    break;
                default:
                    sProxyPhone = new PhoneProxy(new CDMAPhone(context, sCommandsInterface, sPhoneNotifier));
                    break;
            }
        }

        sMadeDefaults = true;
    }
}

類別中對應的欄位宣告為:

static private CommandsInterface sCommandsInterface = null;
// reads the system properties and makes commandsinterface
sCommandsInterface = new RIL(context, networkMode, cdmaSubscription);

所以後續用到的 CommandsInterface 實際型別都是 RIL,因為 RIL 實作了該介面:

public final class RIL extends BaseCommands implements CommandsInterface {}

RIL 是什麼?它位於應用程式框架與 kernel 之間,分成兩部分:rild 負責以 socket 與 framework 溝通;Vendor RIL 則向下透過 AT 指令通道與 radio 通訊,另有專門傳輸封包資料的通道供上網使用。在 Java 框架側又分為 RIL 模組(與 rild 通訊)與 Phone 模組(對應用開發者暴露電話功能介面)。

三、依網路類型建立對應的 Phone

下面的片段依 phoneType 建立不同實作,並以「向上轉型」存進 sProxyPhone。向上轉型是安全的,因為 GSMPhone/CDMAPhone 都繼承自 PhoneBase。

int phoneType = getPhoneType(networkMode);
if (phoneType == Phone.PHONE_TYPE_GSM) {
    sProxyPhone = new PhoneProxy(new GSMPhone(context, sCommandsInterface, sPhoneNotifier));
} else if (phoneType == Phone.PHONE_TYPE_CDMA) {
    switch (BaseCommands.getLteOnCdmaModeStatic()) {
        case Phone.LTE_ON_CDMA_TRUE:
            sProxyPhone = new PhoneProxy(new CDMALTEPhone(context, sCommandsInterface, sPhoneNotifier));
            break;
        default:
            sProxyPhone = new PhoneProxy(new CDMAPhone(context, sCommandsInterface, sPhoneNotifier));
            break;
    }
}

以下以預設的 GSMPhone 為例,看它的建構子:

public GSMPhone(Context context, CommandsInterface ci, PhoneNotifier notifier) {
    this(context, ci, notifier, false);
}

public GSMPhone(Context context, CommandsInterface ci, PhoneNotifier notifier, boolean unitTestMode) {
    super(notifier, context, ci, unitTestMode);
    if (ci instanceof SimulatedRadioControl) {
        mSimulatedRadioControl = (SimulatedRadioControl) ci;
    }
    mCM.setPhoneType(Phone.PHONE_TYPE_GSM);

    mCT = new GsmCallTracker(this);                          // 通話管理
    mSST = new GsmServiceStateTracker(this);                 // 服務狀態
    mSMS = new GsmSMSDispatcher(this, mSmsStorageMonitor, mSmsUsageMonitor);
    mIccFileHandler = new SIMFileHandler(this);
    mIccRecords = new SIMRecords(this);
    mDataConnectionTracker = new GsmDataConnectionTracker(this);
    mIccCard = new SimCard(this);

    if (!unitTestMode) {
        mSimPhoneBookIntManager = new SimPhoneBookInterfaceManager(this);
        mSimSmsIntManager = new SimSmsInterfaceManager(this, mSMS);
        mSubInfo = new PhoneSubInfo(this);
    }

    mStkService = CatService.getInstance(mCM, mIccRecords, mContext, mIccFileHandler, mIccCard);

    mCM.registerForAvailable(this, EVENT_RADIO_AVAILABLE, null);
    mIccRecords.registerForRecordsLoaded(this, EVENT_SIM_RECORDS_LOADED, null);
    mCM.registerForOffOrNotAvailable(this, EVENT_RADIO_OFF_OR_NOT_AVAILABLE, null);
    mCM.registerForOn(this, EVENT_RADIO_ON, null);
    mCM.setOnUSSD(this, EVENT_USSD, null);
    mCM.setOnSuppServiceNotification(this, EVENT_SSN, null);
    mSST.registerForNetworkAttached(this, EVENT_REGISTERED_TO_NETWORK, null);

    SystemProperties.set(TelephonyProperties.CURRENT_ACTIVE_PHONE,
            String.valueOf(Phone.PHONE_TYPE_GSM));
}

這裡建立了通話管理類 GsmCallTracker,其建構子註冊了狀態變更的監聽:

GsmCallTracker(GSMPhone phone) {
    this.phone = phone;
    cm = phone.mCM;
    cm.registerForCallStateChanged(this, EVENT_CALL_STATE_CHANGE, null);
    cm.registerForOn(this, EVENT_RADIO_AVAILABLE, null);
    cm.registerForNotAvailable(this, EVENT_RADIO_NOT_AVAILABLE, null);
}

四、訊息如何一路傳到應用層

GsmCallTracker 繼承了 Handler,因此所有事件都從 handleMessage 進入:

public void handleMessage(Message msg) {
    AsyncResult ar;
    switch (msg.what) {
        case EVENT_POLL_CALLS_RESULT:
            ar = (AsyncResult) msg.obj;
            if (msg == lastRelevantPoll) {
                needsPoll = false;
                lastRelevantPoll = null;
                handlePollCalls(ar);
            }
            break;

        case EVENT_OPERATION_COMPLETE:
            operationComplete();
            break;

        case EVENT_SWITCH_RESULT:
        case EVENT_CONFERENCE_RESULT:
        case EVENT_SEPARATE_RESULT:
        case EVENT_ECT_RESULT:
            ar = (AsyncResult) msg.obj;
            if (ar.exception != null) {
                phone.notifySuppServiceFailed(getFailedService(msg.what));
            }
            operationComplete();
            break;

        case EVENT_GET_LAST_CALL_FAIL_CAUSE:
            ar = (AsyncResult) msg.obj;
            operationComplete();
            // 判斷掛斷原因,必要時寫入 EventLog 並通知各 connection
            // ...
            updatePhoneState();
            phone.notifyPreciseCallStateChanged();
            break;

        case EVENT_REPOLL_AFTER_DELAY:
        case EVENT_CALL_STATE_CHANGE:
            pollCallsWhenSafe();
            break;

        case EVENT_RADIO_AVAILABLE:
            handleRadioAvailable();
            break;

        case EVENT_RADIO_NOT_AVAILABLE:
            handleRadioNotAvailable();
            break;
    }
}

收到 EVENT_CALL_STATE_CHANGE 後,去向 RIL 索取目前的通話清單:

protected void pollCallsWhenSafe() {
    needsPoll = true;
    if (checkNoOperationsPending()) {
        lastRelevantPoll = obtainMessage(EVENT_POLL_CALLS_RESULT);
        cm.getCurrentCalls(lastRelevantPoll);
    }
}

RIL 中的實作把請求打包後送進 socket 寫入佇列:

public void getCurrentCalls(Message result) {
    RILRequest rr = RILRequest.obtain(RIL_REQUEST_GET_CURRENT_CALLS, result);
    if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest));
    send(rr);
}

private void send(RILRequest rr) {
    if (mSocket == null) {
        rr.onError(RADIO_NOT_AVAILABLE, null);
        rr.release();
        return;
    }
    Message msg = mSender.obtainMessage(EVENT_SEND, rr);
    acquireWakeLock();
    msg.sendToTarget();
}

整個事件通知鏈可以概括成下圖:

五、自己動手做一個縮小版

直接跟蹤 Phone 的實interaction 很吃力,訊息流又長,所以我抽出部分結構自己做了一個可執行的模型,用觀察者模式串起 Application → CallManager → Phone → GsmCallTracker → Activity 這條鏈。

專案結構:

PhoneApp:全域初始化

package com.dzt.phonemsg;

import android.app.Application;
import android.util.Log;

import com.dzt.phonemsg.framework.CallManager;
import com.dzt.phonemsg.framework.Phone;

/**
 * 演示 Phone 程式中的事件傳遞。
 * 由於 Phone 應用程式在追蹤時不方便、訊息通訊也較複雜,
 * 這裡抽出部分程式碼用 Handler 模擬訊息傳遞,並用到觀察者模式。
 */
public class PhoneApp extends Application {

    private static final String TAG = "PhoneApp_dzt";
    private static final boolean mIsShowLog = true;

    static PhoneApp instance = null;
    Phone phone = new Phone();
    CallManager mCM;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mCM = CallManager.getInstance();
        mCM.registerPhone(phone);
        print_i("PhoneApp", "onCreate");
    }

    static PhoneApp getInstance() {
        return instance;
    }

    static boolean isRunning() {
        return instance != null;
    }

    public static void print_i(String pkg, String msg) {
        if (mIsShowLog) Log.i(TAG, "[" + pkg + "]-------------------->" + msg);
    }
}

InCallScreen:註冊狀態變更並更新 UI

package com.dzt.phonemsg;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import com.dzt.phonemsg.framework.CallManager;
import com.dzt.phonemsg.framework.Phone;
import com.dzt.phonemsg.os.AsyncResult;

public class InCallScreen extends Activity {

    private static final int PHONE_STATE_CHANGED = 101;
    private static final int REQUEST_UPDATE_SCREEN = 122;

    private TextView mText = null;
    private Phone.State mState = Phone.State.IDLE;
    private CallManager mCM;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mText = (TextView) findViewById(R.id.tv_text);
        mCM = PhoneApp.getInstance().mCM;
        registerForPhoneStates();
    }

    @Override
    protected void onDestroy() {
        if (PhoneApp.isRunning()) {
            PhoneApp.getInstance().phone.exitPhone();
        }
        super.onDestroy();
    }

    /** 電話狀態改變了,更新畫面 */
    private void onPhoneStateChanged(AsyncResult r) {
        mState = mCM.getState();
        requestUpdateScreen();
    }

    /** 向 CallManager 註冊狀態變更通知 */
    private void registerForPhoneStates() {
        mCM.registerForPreciseCallStateChanged(mHandler, PHONE_STATE_CHANGED, null);
    }

    void requestUpdateScreen() {
        PhoneApp.print_i("MainActivity", "requestUpdateScreen()...");
        mHandler.removeMessages(REQUEST_UPDATE_SCREEN);
        mHandler.sendEmptyMessage(REQUEST_UPDATE_SCREEN);
    }

    /** 真正操作 UI 的地方:更新通話狀態與時間 */
    private void updateScreen() {
        mText.setText(mState.toString());
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PHONE_STATE_CHANGED:
                    onPhoneStateChanged((AsyncResult) msg.obj);
                    break;
                case REQUEST_UPDATE_SCREEN:
                    updateScreen();
                    break;
                default:
                    break;
            }
        }
    };
}

GsmCallTracker:隨機改變狀態模擬通話

package com.dzt.phonemsg.framework;

import java.util.Random;

/** 隨機改變狀態,模擬通話管理 */
public class GsmCallTracker {

    Phone.State state = Phone.State.IDLE;
    boolean mIsRunning = false;
    Phone mPhone = null;

    GsmCallTracker(Phone phone) {
        mIsRunning = true;
        mPhone = phone;
        new CallTrackerThread().start();
    }

    public void exitGsmCallTracker() {
        mIsRunning = false;
    }

    class CallTrackerThread extends Thread {
        @Override
        public void run() {
            while (mIsRunning) {
                Random random = new Random();
                switch (random.nextInt(3)) {
                    case 0:  state = Phone.State.IDLE;     break;
                    case 1:  state = Phone.State.RINGING;  break;
                    case 2:  state = Phone.State.OFFHOOK;  break;
                    default: state = Phone.State.IDLE;     break;
                }
                mPhone.notifyPreciseCallStateChanged();   // 觸發觀察者鏈
                try {
                    sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

執行結果:

六、這條鏈的重點

  • 工廠 + 代理:PhoneFactory 依網路模式產生實作,外層一律以 PhoneProxy 包住,應用層完全不感知差異。
  • 唯一性靠 socket 保證:LocalServerSocket("com.android.internal.telephony") 若綁定失敗就重試,超過上限即判定 PhoneFactory 已初始化,是一個相當巧妙的單例守衛。
  • 一切皆訊息:RIL 的請求與回應、狀態變更,全部走 Handler/Message。理解 registerForXxx 與 notifyXxx 成對出現的規律,讀這部分碼的效率會大幅提升。
  • Handler 必須綁 Looper 執行緒:這也是 makeDefaultPhone 一開頭就檢查 Looper.myLooper() 不為 null 的原因。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved