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

Android 6.0 來電(MT)流程源碼全解析

編輯:關於 Android 程式設計

本文基於對 telephony 模塊的研究,結合網上資料與個人理解,總結了 Android 6.0 中 MT(Mobile Terminated,移動主叫被叫,即來電)的完整流程。先放出 6.0 的 MT 時序圖,便於建立直觀認識,下面再結合代碼逐步分析。

第一部分:RIL → GSMPhone → 發出來電通知

(涉及 frameworks/opt/telephony)

1. RIL.java

RIL-Java 本質上是一個 RIL 代理,起到轉發作用,是 Android Java 空間中電話系統的起點。當它接收到 RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED 消息後,會通過 mCallStateRegistrants.notifyRegistrants 發出通知:

private void processUnsolicited(Parcel p) {
    switch (response) {
        case RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED:
            mCallStateRegistrants.notifyRegistrants(new AsyncResult(null, null, null));
            ...
    }
}

BaseCommands.java 中的 registerForCallStateChanged 負責把觀察者加入列表:

@Override
public void registerForCallStateChanged(Handler h, int what, Object obj) {
    Registrant r = new Registrant(h, what, obj);
    mCallStateRegistrants.add(r);
}

重點 1:這其實是觀察者模式的一種實現。RegistrantList 是通知者,Registrant 是觀察者,二者是一對多關係。當事件更新時,所有在名單上登記過的對象都會收到通知。整個機制分為消息註冊與消息通知兩部分:調用 regist 時把 Message 存進去,調用 notify 時把所有 Message 取出並發送到 MessageQueue 中等待處理。

2. GSMCallTracker.java

GSMCallTracker 本質上是一個 Handler,是 Android 的通話管理層。它用 ConnectionList 管理現行的通話連接,並向上層提供電話調用接口。它通過 registerForCallStateChanged 註冊,並在 handleMessage 中處理 EVENT_CALL_STATE_CHANGE:

mCi.registerForCallStateChanged(this, EVENT_CALL_STATE_CHANGE, null);

@Override
public void handleMessage(Message msg) {
    case EVENT_CALL_STATE_CHANGE:
        pollCallsWhenSafe(); // 查詢 Call List
        break;
}

3. pollCallsWhenSafe()(在 CallTracker.java 中實現)

protected void pollCallsWhenSafe() {
    mNeedsPoll = true;
    if (checkNoOperationsPending()) {
        mLastRelevantPoll = obtainMessage(EVENT_POLL_CALLS_RESULT);
        mCi.getCurrentCalls(mLastRelevantPoll); // 向 RIL 查詢當前通話列表
    }
}

回到 RIL.java 的 getCurrentCalls,把 RIL_REQUEST_GET_CURRENT_CALLS 封裝成 RILRequest 並發送:

@Override
public void getCurrentCalls(Message result) {
    RILRequest rr = RILRequest.obtain(RIL_REQUEST_GET_CURRENT_CALLS, result);
    send(rr);
}

真正的邏輯處理在 processSolicited 中,處理完後把結果回傳:

private RILRequest processSolicited(Parcel p) {
    case RIL_REQUEST_GET_CURRENT_CALLS:
        ret = responseCallList(p);
        break;
    if (rr.mResult != null) {
        AsyncResult.forMessage(rr.mResult, ret, null);
        rr.mResult.sendToTarget(); // 發出 handler 通知
    }
}

4. 回到 GSMCallTracker 的 handleMessage

rr.mResult.sendToTarget() 發出通知後,會在 GSMCallTracker 的 handleMessage 中響應,消息類型為 EVENT_POLL_CALLS_RESULT:

case EVENT_POLL_CALLS_RESULT:
    ar = (AsyncResult) msg.obj;
    if (msg == mLastRelevantPoll) {
        mNeedsPoll = false;
        mLastRelevantPoll = null;
        handlePollCalls((AsyncResult) msg.obj);
    }
    break;

5. handlePollCalls 根據 Call List 判斷狀態並發出通知

該方法根據 RIL 返回的 Call List 判斷狀態,發出不同通知:來電時發出 phone.notifyNewRingingConnection,通話斷開發出 onDisconnected,狀態變化則通知 phone.notifyPreciseCallStateChanged。來電時進入 notifyNewRingingConnection:

if (newRinging != null) {
    mPhone.notifyNewRingingConnection(newRinging);
}

6. GSMPhone.java

public void notifyNewRingingConnection(Connection c) {
    super.notifyNewRingingConnectionP(c);
}

其父類 PhoneBase.java 中的 notifyNewRingingConnectionP 發出來電通知:

public void notifyNewRingingConnectionP(Connection cn) {
    if (!mIsVoiceCapable) return;
    AsyncResult ar = new AsyncResult(null, cn, null);
    mNewRingingConnectionRegistrants.notifyRegistrants(ar);
}

重點 2:RegistrantList.java 位於 frameworks/base/core/java/android/os。其 notifyRegistrants 通過遍歷 registrants,對每個 Registrant 調用 internalNotifyRegistrant,最終封裝成 Message 發送給對應的 Handler 處理。

註冊為觀察者的方法是 registerForNewRingingConnection,而通過 log 可以看到是 PstnIncomingCallNotifier.java 調用了它:

01-05 07:10:05.517 1596 1596 D Telephony: PstnIncomingCallNotifier: handleNewRingingConnection

第二部分:PstnIncomingCallNotifier → 準備創建連接

(packages/services/Telephony)

7. PstnIncomingCallNotifier.java

它負責監聽相關電話對象的來電事件,並通知 Telecom。registerForNotifications 中調用了 registerForNewRingingConnection:

private void registerForNotifications() {
    Phone newPhone = mPhoneProxy.getActivePhone();
    if (newPhone != mPhoneBase) {
        unregisterForNotifications();
        if (newPhone != null) {
            mPhoneBase = newPhone;
            mPhoneBase.registerForNewRingingConnection(mHandler, EVENT_NEW_RINGING_CONNECTION, null);
            mPhoneBase.registerForCallWaiting(mHandler, EVENT_CDMA_CALL_WAITING, null);
            mPhoneBase.registerForUnknownConnection(mHandler, EVENT_UNKNOWN_CONNECTION, null);
        }
    }
}

8. handle 處理 EVENT_NEW_RINGING_CONNECTION

private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        case EVENT_NEW_RINGING_CONNECTION:
            handleNewRingingConnection((AsyncResult) msg.obj);
            break;
    }
};

9. handleNewRingingConnection 處理新來電連接

private void handleNewRingingConnection(AsyncResult asyncResult) {
    Connection connection = (Connection) asyncResult.result;
    if (connection != null) {
        Call call = connection.getCall();
        // 發送 intent 到 Telecom 前,最後一次驗證 ringing 狀態
        if (call != null && call.getState().isRinging()) {
            sendIncomingCallIntent(connection);
        }
    }
}

10. sendIncomingCallIntent 發送 intent 到 Telecom

private void sendIncomingCallIntent(Connection connection) {
    Bundle extras = null;
    if (connection.getNumberPresentation() == TelecomManager.PRESENTATION_ALLOWED
            && !TextUtils.isEmpty(connection.getAddress())) {
        extras = new Bundle();
        Uri uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, connection.getAddress(), null);
        extras.putParcelable(TelephonyManager.EXTRA_INCOMING_NUMBER, uri);
    }
    TelecomManager.from(mPhoneProxy.getContext()).addNewIncomingCall(
        TelecomAccountRegistry.makePstnPhoneAccountHandle(mPhoneProxy), extras);
}

11. TelecomManager.addNewIncomingCall

位於 frameworks/base/telecomm/java/android/telecom/TelecomManager.java,它封裝了 TelecomService 的遠程接口供應用使用:

public void addNewIncomingCall(PhoneAccountHandle phoneAccount, Bundle extras) {
    try {
        if (isServiceConnected()) {
            getTelecomService().addNewIncomingCall(phoneAccount, extras == null ? new Bundle() : extras);
        }
    } catch (RemoteException e) {
        Log.e(TAG, "RemoteException adding a new incoming call: " + phoneAccount, e);
    }
}

12. TelecomServiceImpl.addNewIncomingCall

位於 packages/services/Telecomm/src/com/android/server/telecom/TelecomServiceImpl.java,構建 Intent 並交給 CallIntentProcessor 處理:

@Override
public void addNewIncomingCall(PhoneAccountHandle phoneAccountHandle, Bundle extras) {
    synchronized (mLock) {
        Intent intent = new Intent(TelecomManager.ACTION_INCOMING_CALL);
        intent.putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, phoneAccountHandle);
        intent.putExtra(CallIntentProcessor.KEY_IS_INCOMING_CALL, true);
        if (extras != null) {
            intent.putExtra(TelecomManager.EXTRA_INCOMING_CALL_EXTRAS, extras);
        }
        CallIntentProcessor.processIncomingCallIntent(mCallsManager, intent);
    }
}

13. CallsManager.processIncomingCallIntent

CallsManager 提供了一個抽象層,供 phoneApp 訪問和控制通話,實現了 Phone 接口,提供呼叫控制、Channel 能力與通知註冊三類 API。它 new 一個 Call 對象並調用 startCreateConnection 開始建立連接:

Call call = new Call(mContext, this, mLock, mConnectionServiceRepository,
    mContactsAsyncHelper, mCallerInfoAsyncQueryFactory, handle,
    null, null, phoneAccountHandle, true, false);
call.setIntentExtras(extras);
call.addListener(this);
call.startCreateConnection(mPhoneAccountRegistrar);

14. Call.startCreateConnection

Call 封裝了通話在其整個生命週期中的各個方面。它創建 CreateConnectionProcessor 並執行:

void startCreateConnection(PhoneAccountRegistrar phoneAccountRegistrar) {
    mCreateConnectionProcessor = new CreateConnectionProcessor(
        this, mRepository, this, phoneAccountRegistrar, mContext);
    mCreateConnectionProcessor.process();
}

第三部分:建立連接 → 成功來電 → 準備啟動界面

15. CreateConnectionProcessor.process

它組織 CallAttemptRecord 並嘗試下一個 PhoneAccount:

void process() {
    mAttemptRecords = new ArrayList<>();
    adjustAttemptsForConnectionManager();
    adjustAttemptsForEmergency();
    mAttemptRecordIterator = mAttemptRecords.iterator();
    attemptNextPhoneAccount();
}

16. attemptNextPhoneAccount 讓 Service 嘗試建立連接

ConnectionServiceWrapper service = mRepository.getService(
    attempt.connectionManagerPhoneAccount.getComponentName());
if (service == null) {
    attemptNextPhoneAccount();
} else {
    mCall.setConnectionService(service);
    service.createConnection(mCall, new Response(service));
}

17. ConnectionServiceWrapper.createConnection

負責為撥出的電話建立連接,或關聯一個已存在的來電:

void createConnection(final Call call, final CreateConnectionResponse response) {
    mBinder.bind(callback);
}

18. ServiceBinder.bind

ServiceBinder 是抽象類,負責綁定到指定服務接口。它執行綁定操作並在成功/失敗時觸發相應回調:

void bind(BindCallback callback, Call call) {
    clearAbort();
    mCallbacks.add(callback);
    if (mServiceConnection == null) {
        Intent serviceIntent = new Intent(mServiceAction).setComponent(mComponentName);
        ServiceConnection connection = new ServiceBinderConnection(call);
        final int bindingFlags = Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE;
        final boolean isBound = mContext.bindService(serviceIntent, connection, bindingFlags);
        if (!isBound) {
            handleFailedConnection();
        }
    } else {
        handleSuccessfulConnection();
    }
}

19. onServiceConnected → handleSuccessfulConnection

綁定成功後,ServiceBinderConnection 的 onServiceConnected 會被調用,進而執行 handleSuccessfulConnection,遍歷回調每一個 BindCallback 的 onSuccess。

20. ConnectionService.createConnection

位於 frameworks/base/telecomm/java/android/telecom/ConnectionService.java,它提供電話連接到 Android 設備的進程。createConnection 通過 Handler 發送 MSG_CREATE_CONNECTION 消息,最終判斷來電類型並調用 onCreateIncomingConnection 等創建連接:

private void createConnection(final PhoneAccountHandle callManagerAccount, final String callId,
        final ConnectionRequest request, boolean isIncoming, boolean isUnknown) {
    Connection connection = isUnknown ? onCreateUnknownConnection(callManagerAccount, request)
        : isIncoming ? onCreateIncomingConnection(callManagerAccount, request)
        : onCreateOutgoingConnection(callManagerAccount, request);
    ...
    mAdapter.handleCreateConnectionComplete(callId, request, connection);
}

21. ConnectionServiceAdapter.handleCreateConnectionComplete

它遍歷 mAdapters,把連接完成事件回傳給各個 IConnectionServiceAdapter:

void handleCreateConnectionComplete(String id, ConnectionRequest request, ParcelableConnection connection) {
    for (IConnectionServiceAdapter adapter : mAdapters) {
        adapter.handleCreateConnectionComplete(id, request, connection);
    }
}

22. ConnectionServiceWrapper 處理成功連接

Telecomm 層的連接管理者。若連接狀態為 DISCONNECTED 視為失敗並移除;否則視為成功並回調 handleCreateConnectionSuccess:

private void handleCreateConnectionComplete(String callId, ConnectionRequest request, ParcelableConnection connection) {
    if (connection.getState() == Connection.STATE_DISCONNECTED) {
        removeCall(callId, connection.getDisconnectCause());
    } else {
        mPendingResponses.get(callId).handleCreateConnectionSuccess(mCallIdMapper, connection);
    }
}

23. Call.handleCreateConnectionSuccess

它設置目標賬號、handle、來電顯示等信息。對於來電(mIsIncoming),不會立即處理,而是啟動一個 mDirectToVoicemailRunnable,先查詢「直接轉語音信箱」屬性,再決定是否展示來電界面或拒接:

} else if (mIsIncoming) {
    mDirectToVoicemailQueryPending = true;
    mHandler.postDelayed(mDirectToVoicemailRunnable,
        Timeouts.getDirectToVoicemailMillis(mContext.getContentResolver()));
}

24. processDirectToVoicemail → onSuccessfulIncomingCall

若需要轉語音信箱則 reject,否則遍歷 Listener 調用 onSuccessfulIncomingCall。隨後在 CallsManager 中:

@Override
public void onSuccessfulIncomingCall(Call incomingCall) {
    setCallState(incomingCall, CallState.RINGING);
    if (hasMaximumRingingCalls(incomingCall.getTargetPhoneAccount().getId())) {
        incomingCall.reject(false, null);
        mMissedCallNotifier.showMissedCallNotification(incomingCall);
        mCallLogManager.logCall(incomingCall, Calls.MISSED_TYPE);
    } else {
        incomingCall.mIsActiveSub = true;
        addCall(incomingCall);
        setActiveSubscription(incomingCall.getTargetPhoneAccount().getId());
    }
}

addCall 會把通話加入列表並通知各 CallsManagerListener:

private void addCall(Call call) {
    call.addListener(this);
    mCalls.add(call);
    for (CallsManagerListener listener : mListeners) {
        listener.onCallAdded(call);
    }
    updateForegroundCall();
}

第四部分:CallList → InCallActivity → 顯示來電

25. InCallController.onCallAdded

位於 packages/services/Telecomm/src/com/android/server/telecom/InCallController.java,負責把更新發送給通話程序。它遍歷 mInCallServices,把 ParcelableCall 添加到各 InCallService:

@Override
public void onCallAdded(Call call) {
    if (!isBoundToServices()) {
        bindToServices(call);
    } else {
        addCall(call);
        for (Map.Entry entry : mInCallServices.entrySet()) {
            IInCallService inCallService = entry.getValue();
            ParcelableCall parcelableCall = toParcelableCall(call, true);
            inCallService.addCall(parcelableCall);
        }
    }
}

26. InCallService.addCall

位於 frameworks/base/telecomm/java/android/telecom/InCallService.java,任何希望提供通話管理界面的應用都可實現它。其內部 InCallServiceBinder 把 addCall 封裝成 MSG_ADD_CALL 消息:

@Override
public void addCall(ParcelableCall call) {
    mHandler.obtainMessage(MSG_ADD_CALL, call).sendToTarget();
}

handleMessage 處理 MSG_ADD_CALL,調用 mPhone.internalAddCall。

27. Phone.internalAddCall

位於 frameworks/base/telecomm/java/android/telecom/Phone.java,創建 Call 對象並觸發 fireCallAdded:

final void internalAddCall(ParcelableCall parcelableCall) {
    Call call = new Call(this, parcelableCall.getId(), mInCallAdapter, parcelableCall.mIsActiveSub);
    mCallByTelecomCallId.put(parcelableCall.getId(), call);
    mCalls.add(call);
    call.internalUpdate(parcelableCall, mCallByTelecomCallId);
    fireCallAdded(call);
}

28. CallList.onCallAdded

位於 packages/apps/InCallUI/src/com/android/incallui/CallList.java,保持活動通話列表並通知感興趣的類。它通過 Phone.Listener 的 onCallAdded 判斷來電狀態並調用 onIncoming:

@Override
public void onCallAdded(Phone phone, android.telecom.Call telecommCall) {
    Call call = new Call(telecommCall);
    if (call.getState() == Call.State.INCOMING) {
        onIncoming(call, call.getCannedSmsResponses());
    } else {
        onUpdate(call);
    }
}

29. InCallPresenter.onIncomingCall

位於 InCallPresenter.java,負責為新通話啟動 Activity。它切換 InCallState 並通知 IncomingCallListener:

@Override
public void onIncomingCall(Call call) {
    InCallState newState = startOrFinishUi(InCallState.INCOMING);
    InCallState oldState = mInCallState;
    mInCallState = newState;
    for (IncomingCallListener listener : mIncomingCallListeners) {
        listener.onIncomingCall(oldState, mInCallState, call);
    }
}

30. showInCall 啟動界面

最終通過 startUi → showInCall 啟動 InCallActivity,把來電界面呈現給用戶:

public void showInCall(final boolean showDialpad, final boolean newOutgoingCall) {
    mContext.startActivity(getInCallIntent(showDialpad, newOutgoingCall));
}

總結

整體來看,Android 6.0 的 MT 來電流程可以概括為四個階段:首先,RIL 接收到來電狀態變化,經由 GSMCallTracker 拉取通話列表並逐層上報,最終由 PhoneBase 發出來電通知;接著,PstnIncomingCallNotifier 監聽到通知後,構造 Intent 交給 Telecom;然後,Telecom 通過 CallsManager、Call、CreateConnectionProcessor、ConnectionService 等一系列組件完成連接的建立與成功回調;最後,InCallController 把通話分發給 InCallService,經由 Phone、CallList、InCallPresenter,最終啟動 InCallActivity 顯示來電界面。這條鏈路層層解耦、逐級回調,正是 Android 通話框架設計的精妙之處。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved