当前位置:   article > 正文

安卓10拨号流程梳理_newoutgoingcallintentbroadcaster如何实现紧急电话呼叫

newoutgoingcallintentbroadcaster如何实现紧急电话呼叫

电话应用框架

Android电话模块是一个典型的分层结构设计,如下:

电话框架分为4个层次,分别为:应用层、框架层(framework层,简称fw)、RIL(Radio Interface Layer)、modem。

应用层:app应用,包括Dialer.apk、TeleService.apk、Telecom.apk、InCallUI.apk。

其中Dialer.apk跑在com.android.dialer进程中,TeleService.apk跑在常驻进程com.android.phone进程中,Telecom.apk跑在system进程中、InCallUI.apk跑在com.android.incallui进程中。

框架层:包括telephony fw、telecom fw。Code分别位于frameworks/opt/telephony、frameworks/base/telecomm。

RIL:位于User Libraries层中的HAL层,提供AP(Application Processor,应用处理器)和BP(Baseband Processor,基带处理器)之间的通信功能。RIL通常分为RILJ、RILC,RILJ即为java的RIL.java,code位于框架层,RILC才是真正的RIL层。Android的RIL驱动模块,在hardware/ril目录下,一共分rild,libril.so以及librefrence_ril.so三个部分。

Modem:位于BP,负责实际的无线通信能力处理

 实现各进程交互的aidl:

 拨号流程框架流程

 

  • packages/apps/Dialer/java/com/android/dialer/dialpadview/DialpadFragment.java

用户点击拨号盘的拨号按钮,此时开始呼叫长征第一步,dialpadfragment的onclick方法会响应点击事件。 

  1. @Override
  2. public void onClick(View view) {
  3. int resId = view.getId();
  4. if (resId == R.id.dialpad_floating_action_button) {
  5. view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
  6. handleDialButtonPressed();
  7. }

找到拨号界面对应的l ayout 界面布局文件dialer/dialpadview/res/layout/dialpad_fragment.xml ,其中就包含了打开拨号盘的浮动按钮,其定义如下 

 在该类中 运行:handleDialButtonPressed(); 方法,判断是否号码是否为空,是否非法等情况

 

10 之前没有这一步,直接调用 DialerUtils.startActivityWithErrorToast() 方法

携带Intent.ACTION_CALL的Intent Action会走到TelecomUtil placeCall流程,否则直接context.startActivity(intent);

  1. public static void startActivityWithErrorToast(
  2. final Context context, final Intent intent, int msgId) {
  3. try {
  4. if ((Intent.ACTION_CALL.equals(intent.getAction()))) {
  5. placeCallOrMakeToast(context, intent);
  6. } else {
  7. context.startActivity(intent);

startActivityWithErrorToast() 方法 调用下列方法

hasCallPhonePermission()会检查是否有呼叫权限,是否有Manifest.permission.CALL_PHONE)权限:

  1. private static void placeCallOrMakeToast(Context context, Intent intent) {
  2. final boolean hasCallPermission = TelecomUtil.placeCall(context, intent);
  3. if (!hasCallPermission) {
  4. Toast.makeText(context, "Cannot place call without Phone permission", Toast.LENGTH_SHORT)
  5. .show();
  6. }
  7. }
  1. public static boolean placeCall(Context context, Intent intent) {
  2. if (hasCallPhonePermission(context)) {
  3. getTelecomManager(context).placeCall(intent.getData(), intent.getExtras());
  4. return true;
  5. }
  6. return false;
  7. }

TelecomManager.placeCall主要获取TelecomService的Binder接口,跨进程进入到TelecomService(system进程)内部,至此 com.android.dialer 进程的工作暂时完成

  1. private static TelecomManager getTelecomManager(Context context) {
  2. return (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
  3. }

Telecom Manager 获取ITelecomService 服务并调用其placeCall 方法继续传递intent 发出通话呼叫请求,将涉及第一次跨进程的服务调用。

  1. public void placeCall(Uri address, Bundle extras) {
  2. ITelecomService service = getTelecomService();
  3. if (service != null) {
  4. if (address == null) {
  5. Log.w(TAG, "Cannot place call to empty address.");
  6. }
  7. try {
  8. service.placeCall(address, extras == null ? new Bundle() : extras,
  9. mContext.getOpPackageName());
  10. } catch (RemoteException e) {
  11. Log.e(TAG, "Error calling ITelecomService#placeCall", e);
  12. }
  13. }
  14. }

其中,getTelecomService() 方法

  1. private ITelecomService getTelecomService() {
  2. if (mTelecomServiceOverride != null) {
  3. return mTelecomServiceOverride;
  4. }
  5. return ITelecomService.Stub.asInterface(ServiceManager.getService(Context.TELECOM_SERVICE));
  6. }

调用ITelecomService的placeCall方法,此处是aidl调用,对应的我们需要找到接收的地方,按照命名规则应该是TelecomServiceImpl:

创建UserCallIntentProcessorFactory,调用processIntent方法处理呼叫:

  1. private final ITelecomService.Stub mBinderImpl = new ITelecomService.Stub() {
  2. @Override
  3. public void placeCall(Uri handle, Bundle extras, String callingPackage) {
  4. try {
  5. synchronized (mLock) {
  6. final UserHandle userHandle = Binder.getCallingUserHandle();
  7. long token = Binder.clearCallingIdentity();
  8. try {
  9. final Intent intent = new Intent(Intent.ACTION_CALL, handle);
  10. mUserCallIntentProcessorFactory.create(mContext, userHandle)
  11. .processIntent(
  12. intent, callingPackage, hasCallAppOp && hasCallPermission);
  13. }
  14. }
  15. }
  16. }
  17. }

processIntent判断是否是呼叫请求: 

  1. public void processIntent(Intent intent, String callingPackageName,
  2. boolean canCallNonEmergency, boolean isLocalInvocation) {
  3. // Ensure call intents are not processed on devices that are not capable of calling.
  4. if (!isVoiceCapable()) {
  5. return;
  6. }
  7. String action = intent.getAction();
  8. if (Intent.ACTION_CALL.equals(action) ||
  9. Intent.ACTION_CALL_PRIVILEGED.equals(action) ||
  10. Intent.ACTION_CALL_EMERGENCY.equals(action)) {
  11. processOutgoingCallIntent(intent, callingPackageName, canCallNonEmergency,
  12. isLocalInvocation);
  13. }
  14. }
  • Intent.ACTION_CALL: 可以拨打普通呼叫
public static final String ACTION_CALL = "android.intent.action.CALL";
  • Intent.ACTION_CALL_PRIVILEGED:可以拨打任意类型号码
public static final String ACTION_CALL_PRIVILEGED = "android.intent.action.CALL_PRIVILEGED";
  • Intent.ACTION_CALL_EMERGENCY:可以拨打紧急呼叫
public static final String ACTION_CALL_EMERGENCY = "android.intent.action.CALL_EMERGENCY";

processOutgoingCallIntent方法:

  1. private void processOutgoingCallIntent(Intent intent, String callingPackageName,
  2. boolean canCallNonEmergency, boolean isLocalInvocation) {
  3. ------
  4. ------
  5. int videoState = intent.getIntExtra(
  6. TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE,
  7. VideoProfile.STATE_AUDIO_ONLY);
  8. Log.d(this, "processOutgoingCallIntent videoState = " + videoState);
  9. intent.putExtra(CallIntentProcessor.KEY_IS_PRIVILEGED_DIALER,
  10. isDefaultOrSystemDialer(callingPackageName));
  11. // Save the user handle of current user before forwarding the intent to primary user.
  12. intent.putExtra(CallIntentProcessor.KEY_INITIATING_USER, mUserHandle);
  13. sendIntentToDestination(intent, isLocalInvocation, callingPackageName);
  14. }

sendIntentToDestination 方法:

  1. private boolean sendIntentToDestination(Intent intent, boolean isLocalInvocation,
  2. String callingPackage) {
  3. intent.putExtra(CallIntentProcessor.KEY_IS_INCOMING_CALL, false);
  4. intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
  5. if (isLocalInvocation) {
  6. // We are invoking this from TelecomServiceImpl, so TelecomSystem is available. Don't
  7. // bother trampolining the intent, just sent it directly to the call intent processor.
  8. // TODO: We should not be using an intent here; this whole flows needs cleanup.
  9. Log.i(this, "sendIntentToDestination: send intent to Telecom directly.");
  10. synchronized (TelecomSystem.getInstance().getLock()) {
  11. TelecomSystem.getInstance().getCallIntentProcessor().processIntent(intent,
  12. callingPackage);
  13. }
  14. } else {
  15. // We're calling from the UserCallActivity, so the TelecomSystem is not in the same
  16. // process; we need to trampoline to TelecomSystem in the system server process.
  17. Log.i(this, "sendIntentToDestination: trampoline to Telecom.");
  18. TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
  19. tm.handleCallIntent(intent);
  20. }
  21. return true;
  22. }

安卓10 这里去除了以前的广播机制

调用getTelecomSystem方法返回TelecomSystem对象,调用getCallIntentProcessor()返回CallIntentProcessor对象,然后调用processIntent方法

  1. public void processIntent(Intent intent, String callingPackage) {
  2. final boolean isUnknownCall = intent.getBooleanExtra(KEY_IS_UNKNOWN_CALL, false);
  3. Log.i(this, "onReceive - isUnknownCall: %s", isUnknownCall);
  4. Trace.beginSection("processNewCallCallIntent");
  5. if (isUnknownCall) {
  6. processUnknownCallIntent(mCallsManager, intent);
  7. } else {
  8. processOutgoingCallIntent(mContext, mCallsManager, intent, callingPackage);
  9. }
  10. Trace.endSection();
  11. }

processOutgoingCallIntent方法,调用CallsManager的startOutgoingCall()方法创建Call,后new NewOutgoingCallIntentBroadcaster,调用processIntent()方法:

CallsManager 创建Call, 链接,监听Call状态

下面先分析  startOutgoingCall()方法, 

再分析 new NewOutgoingCallIntentBroadcaster,的processIntent()方法

  1. static void processOutgoingCallIntent(
  2. Context context,
  3. CallsManager callsManager,
  4. Intent intent,
  5. String callingPackage) {
  6. --------
  7. // Send to CallsManager to ensure the InCallUI gets kicked off before the broadcast returns
  8. // 先执行此处代码,更新 ui 界面
  9. CompletableFuture<Call> callFuture = callsManager
  10. .startOutgoingCall(handle, phoneAccountHandle, clientExtras, initiatingUser,
  11. intent, callingPackage);
  12. final Session logSubsession = Log.createSubsession();
  13. callFuture.thenAccept((call) -> {
  14. if (call != null) {
  15. Log.continueSession(logSubsession, "CIP.sNOCI");
  16. try {
  17. // 实际的,将上层信息下发到telephony, ril
  18. sendNewOutgoingCallIntent(context, call, callsManager, intent);
  19. } finally {
  20. Log.endSession();
  21. }
  22. }
  23. });
  24. }

其中的 sendNewOutgoingCallIntent 方法如下定义:‘

  1. static void sendNewOutgoingCallIntent(Context context, Call call, CallsManager callsManager,
  2. Intent intent) {
  3. // Asynchronous calls should not usually be made inside a BroadcastReceiver because once
  4. // onReceive is complete, the BroadcastReceiver's process runs the risk of getting
  5. // killed if memory is scarce. However, this is OK here because the entire Telecom
  6. // process will be running throughout the duration of the phone call and should never
  7. // be killed.
  8. final boolean isPrivilegedDialer = intent.getBooleanExtra(KEY_IS_PRIVILEGED_DIALER, false);
  9. NewOutgoingCallIntentBroadcaster broadcaster = new NewOutgoingCallIntentBroadcaster(
  10. context, callsManager, call, intent, callsManager.getPhoneNumberUtilsAdapter(),
  11. isPrivilegedDialer);
  12. // If the broadcaster comes back with an immediate error, disconnect and show a dialog.
  13. NewOutgoingCallIntentBroadcaster.CallDisposition disposition = broadcaster.evaluateCall();
  14. if (disposition.disconnectCause != DisconnectCause.NOT_DISCONNECTED) {
  15. disconnectCallAndShowErrorDialog(context, call, disposition.disconnectCause);
  16. return;
  17. }
  18. broadcaster.processCall(disposition);
  19. }
  1. public void processCall(CallDisposition disposition) {
  2. if (disposition.callImmediately) {
  3. boolean speakerphoneOn = mIntent.getBooleanExtra(
  4. TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, false);
  5. int videoState = mIntent.getIntExtra(
  6. TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE,
  7. VideoProfile.STATE_AUDIO_ONLY);
  8. placeOutgoingCallImmediately(mCall, disposition.callingAddress, null,
  9. speakerphoneOn, videoState);
  10. // Don't return but instead continue and send the ACTION_NEW_OUTGOING_CALL broadcast
  11. // so that third parties can still inspect (but not intercept) the outgoing call. When
  12. // the broadcast finally reaches the OutgoingCallBroadcastReceiver, we'll know not to
  13. // initiate the call again because of the presence of the EXTRA_ALREADY_CALLED extra.
  14. }

其中 placeOutgoingCallImmediately 代码:

  1. private void placeOutgoingCallImmediately(Call call, Uri handle, GatewayInfo gatewayInfo,
  2. boolean speakerphoneOn, int videoState) {
  3. Log.i(this,
  4. "Placing call immediately instead of waiting for OutgoingCallBroadcastReceiver");
  5. // Since we are not going to go through "Outgoing call broadcast", make sure
  6. // we mark it as ready.
  7. mCall.setNewOutgoingCallIntentBroadcastIsDone();
  8. mCallsManager.placeOutgoingCall(call, handle, gatewayInfo, speakerphoneOn, videoState);
  9. }

 

先执行了 startOutgoingCall 方法 ,然后再 执行 broadcaster. processCall () 方法 

备注:

这里先设置一个分支,先分析 callsManager.startOutgoingCall 方法

CallsManager 的拨号处理流程

CallsManager.statOutgoingCall 的主要逻辑是创建、更新和保存Call 对象

startOutgoingCall 新建一个(或者重用) call, 将CallsManager绑定监听该 call, 然后通知 callsManager 的监听者, 添加了一个 call

  1. Call startOutgoingCall(Uri handle, PhoneAccountHandle phoneAccountHandle, Bundle extras) {
  2. Call call = getNewOutgoingCall(handle);
  3. // 如果是MMI 号码
  4. if ((isPotentialMMICode(handle) || isPotentialInCallMMICode) && !needsAccountSelection) {
  5. // 让CallsManager监听call的行为
  6. call.addListener(this);
  7. } else if (!mCalls.contains(call)) {
  8. // 确保Call不会重复添加(getNewOutgoingCall有重用机制)
  9. // 添加call, 然后callsManager通知监听者,添加了一个call
  10. addCall(call);
  11. }
  12. return call;
  13. }

addCall 方法:addCall 添加call, 然后callsManager通知监听者,添加了一个call

CallsManager对象将保存多个Call 对象到mCalls 集合中, Call 对象则设置Listener 对象为
CallsManager , 对象之间相互引用。而CallsManager 对象通过 mlisteners  发出onCallAdded 消息
回调。那么mlisteners 究竟是什么呢?摘录出CallsManager类的属性定义和构造方法中的关键逻
辑,

CallsManager 的构造函数

  1. CallsManager(
  2. Context context,
  3. TelecomSystem.SyncRoot lock,
  4. ContactsAsyncHelper contactsAsyncHelper,
  5. CallerInfoAsyncQueryFactory callerInfoAsyncQueryFactory,
  6. MissedCallNotifier missedCallNotifier,
  7. PhoneAccountRegistrar phoneAccountRegistrar,
  8. HeadsetMediaButtonFactory headsetMediaButtonFactory,
  9. ProximitySensorManagerFactory proximitySensorManagerFactory,
  10. InCallWakeLockControllerFactory inCallWakeLockControllerFactory) {
  11. // ....
  12. // 在CallsManager构造的时候, 会给CallsManager添加一系列监听者, 当CallsManager变化时,会通知他们
  13. mListeners.add(statusBarNotifier);
  14. mListeners.add(mCallLogManager);
  15. mListeners.add(mPhoneStateBroadcaster);
  16. // 重点关注 InCallController, log中会打印
  17. mListeners.add(mInCallController);
  18. mListeners.add(mRinger);
  19. mListeners.add(new RingbackPlayer(this, playerFactory));
  20. mListeners.add(new InCallToneMonitor(playerFactory, this));
  21. // 监听手机是否是蓝牙、有限耳机、听筒、扬声器模式
  22. mListeners.add(mCallAudioManager);
  23. mListeners.add(missedCallNotifier);
  24. // 语音提示声
  25. mListeners.add(mDtmfLocalTonePlayer);
  26. mListeners.add(mHeadsetMediaButton);
  27. mListeners.add(mProximitySensorManager);
  28. // ...
  29. }

重点关注的是 InCallController,因为 InCallController 监听CallsManager, 收到来自于CallsManager的消息后, 跨进程回到 最初的 com.android.dialer 进程, 通知 UI 发生变化,也就是说 InCallController 是system 进程 主动沟通 com.android.dialer 进程的桥梁,下面详细解释,InCallController时如何沟通 com.android.dialer进程的。

 

InCallController 用于控制电话App的逻辑和UI

lnCallController. onCallAdded 消息回调

  1. public void onCallAdded(Call call) {
  2. // 先判断是否绑定了服务,第一次的话先绑定
  3. if (!isBoundAndConnectedToServices()) {
  4. Log.i(this, "onCallAdded: %s; not bound or connected.", call);
  5. // We are not bound, or we're not connected.
  6. bindToServices(call); // 绑定服务
  7. } else {
  8. // We are bound, and we are connected.
  9. adjustServiceBindingsForEmergency();

其中的   bindToService() 方法:

  1. @VisibleForTesting
  2. public void bindToServices(Call call) {
  3. if (mInCallServiceConnection == null) {
  4. InCallServiceConnection dialerInCall = null;
  5. InCallServiceInfo defaultDialerComponentInfo = getDefaultDialerComponent();
  6. Log.i(this, "defaultDialer: " + defaultDialerComponentInfo);
  7. if (defaultDialerComponentInfo != null &&
  8. !defaultDialerComponentInfo.getComponentName().equals(
  9. mSystemInCallComponentName)) {
  10. // 重点关注创建的InCallServiceBindingConnection 对象
  11. dialerInCall = new InCallServiceBindingConnection(defaultDialerComponentInfo);
  12. }
  13. Log.i(this, "defaultDialer: " + dialerInCall);
  14. InCallServiceInfo systemInCallInfo = getInCallServiceComponent(
  15. mSystemInCallComponentName, IN_CALL_SERVICE_TYPE_SYSTEM_UI);
  16. EmergencyInCallServiceConnection systemInCall =
  17. new EmergencyInCallServiceConnection(systemInCallInfo, dialerInCall);
  18. systemInCall.setHasEmergency(mCallsManager.hasEmergencyCall());
  19. InCallServiceConnection carModeInCall = null;
  20. InCallServiceInfo carModeComponentInfo = getCarModeComponent();
  21. if (carModeComponentInfo != null &&
  22. !carModeComponentInfo.getComponentName().equals(mSystemInCallComponentName)) {
  23. carModeInCall = new InCallServiceBindingConnection(carModeComponentInfo);
  24. }
  25. mInCallServiceConnection =
  26. new CarSwappingInCallServiceConnection(systemInCall, carModeInCall);
  27. }
  28. mInCallServiceConnection.setCarMode(shouldUseCarModeUI());
  29. // Actually try binding to the UI InCallService. If the response
  30. //执行绑定通话界面InCa ll Service 服务的真实操作,判断返回结果
  31. if (mInCallServiceConnection.connect(call) ==
  32. InCallServiceConnection.CONNECTION_SUCCEEDED) {
  33. // Only connect to the non-ui InCallServices if we actually connected to the main UI
  34. // one.
  35. //只有当我们成功连接到通话界面服务后, 才执行连接无界面的IncallService 服务
  36. connectToNonUiInCallServices(call);
  37. mBindingFuture = new CompletableFuture<Boolean>().completeOnTimeout(false,
  38. mTimeoutsAdapter.getCallRemoveUnbindInCallServicesDelay(
  39. mContext.getContentResolver()),
  40. TimeUnit.MILLISECONDS);
  41. } else {
  42. Log.i(this, "bindToServices: current UI doesn't support call; not binding.");
  43. }
  44. }

上述的类中,InCalIServiceConnection 作为lnCallController的内部公有类,

lnCallServiceBindingConnection 、EmergencylnCallServiceConnection 和CarSwappinglnCallServiceConnection这三个类作为lnCallController的内部私有类,

全部继承于lnCallServiceConnection 类。

mInCallServiceConnection.connect(call) 实际调用的是 lnCallServiceBindingConnection 对象的connect 方法,

  1. @Override
  2. public int connect(Call call) {
  3. if (mIsConnected) {
  4. Log.addEvent(call, LogUtils.Events.INFO, "Already connected, ignoring request.");
  5. return CONNECTION_SUCCEEDED;
  6. }
  7. if (call != null && call.isSelfManaged() &&
  8. !mInCallServiceInfo.isSelfManagedCallsSupported()) {
  9. Log.i(this, "Skipping binding to %s - doesn't support self-mgd calls",
  10. mInCallServiceInfo);
  11. mIsConnected = false;
  12. return CONNECTION_NOT_SUPPORTED;
  13. }
  14. // 指明了绑定In CallService . SERVICE_INTERFACE 服务
  15. Intent intent = new Intent(InCallService.SERVICE_INTERFACE);
  16. intent.setComponent(mInCallServiceInfo.getComponentName());
  17. if (call != null && !call.isIncoming() && !call.isExternalCall()){
  18. intent.putExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS,
  19. call.getIntentExtras());
  20. intent.putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE,
  21. call.getTargetPhoneAccount());
  22. }
  23. Log.i(this, "Attempting to bind to InCall %s, with %s", mInCallServiceInfo, intent);
  24. mIsConnected = true;
  25. if (!mContext.bindServiceAsUser(intent, mServiceConnection,
  26. Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE
  27. | Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS,
  28. UserHandle.CURRENT)) {
  29. Log.w(this, "Failed to connect.");
  30. mIsConnected = false;
  31. }
  32. if (call != null && mIsConnected) {
  33. call.getAnalytics().addInCallService(
  34. mInCallServiceInfo.getComponentName().flattenToShortString(),
  35. mInCallServiceInfo.getType());
  36. }
  37. return mIsConnected ? CONNECTION_SUCCEEDED : CONNECTION_FAILED;
  38. }

上述代码中存在一个  mServiceceConnection对象

看一下 ServiceConnection mServiceceConnection 对象

  1. private final ServiceConnection mServiceConnection = new ServiceConnection() {
  2. @Override
  3. public void onServiceConnected(ComponentName name, IBinder service) {
  4. Log.startSession("ICSBC.oSC");
  5. synchronized (mLock) {
  6. try {
  7. Log.d(this, "onServiceConnected: %s %b %b", name, mIsBound, mIsConnected);
  8. mIsBound = true;
  9. if (mIsConnected) {
  10. // Only proceed if we are supposed to be connected.
  11. onConnected(service);
  12. }
  13. } finally {
  14. Log.endSession();
  15. }
  16. }
  17. }

onConnected 方法:其中又有一个onConnected 方法

  1. protected void onConnected(IBinder service) {
  2. boolean shouldRemainConnected =
  3. InCallController.this.onConnected(mInCallServiceInfo, service);
  4. if (!shouldRemainConnected) {
  5. // Sometimes we can opt to disconnect for certain reasons, like if the
  6. // InCallService rejected our initialization step, or the calls went away
  7. // in the time it took us to bind to the InCallService. In such cases, we go
  8. // ahead and disconnect ourselves.
  9. disconnect();
  10. }
  11. }

上面的代码逻辑体现了绑定服务的全部过程。首先,创建lnCallServiceBindingConnection 对象,创建该对象的同时将同步创建一个mServiceConnection 对象,此对象为匿名的ServiceConnection 类型,重写了onServiceConnected 和onServiceDisconnected 方法

;接着,创建action 为lnCallService. SERVICEINTERFACE 的intent 对象,并更新了PhoneAccount 和Call 的一些关键信息;然后,调用Android 系统的bindServiceAsUser 方法绑定服务;最后是绑定服务成功以后的收尾工作--- onConnected 系统回调,

最后,将发起对  InCallController.this.onConnected  的调用, 方法中的主要处理逻辑详情如下:

  1. private boolean onConnected(InCallServiceInfo info, IBinder service) {
  2. Trace.beginSection("onConnected: " + info.getComponentName());
  3. Log.i(this, "onConnected to %s", info.getComponentName());
  4. // 获取IInCallService 服务并保存
  5. IInCallService inCallService = IInCallService.Stub.asInterface(service);
  6. mInCallServices.put(info, inCallService);
  7. try {
  8. //调用服务方法增加IAdapter, InCallAdapter 实现了IInCallAdapter.aidl 接口
  9. inCallService.setInCallAdapter(
  10. new InCallAdapter(
  11. mCallsManager,
  12. mCallIdMapper,
  13. mLock,
  14. info.getComponentName().getPackageName()));
  15. } catch (RemoteException e) {
  16. Log.e(this, e, "Failed to set the in-call adapter.");
  17. Trace.endSection();
  18. return false;
  19. }
  20. // Upon successful connection, send the state of the world to the service.
  21. List<Call> calls = orderCallsWithChildrenFirst(mCallsManager.getCalls());
  22. Log.i(this, "Adding %s calls to InCallService after onConnected: %s, including external " +
  23. "calls", calls.size(), info.getComponentName());
  24. int numCallsSent = 0;
  25. //将之前保存的Call 对象通过inCallService 发送出去
  26. for (Call call : calls) {
  27. try {
  28. //注意这里有Call 对象的转换, 将com.android.server.telecom.Call 转换为可跨进
  29. // 程传递的对象android.telecom.ParcelableCall
  30. parcelableCall = ParcelableCallUtils.toParcelableCall(
  31. call,
  32. true /* includeVideoProvider */,
  33. mCallsManager.getPhoneAccountRegistrar(),
  34. info.isExternalCallsSupported(),
  35. includeRttCall,
  36. info.getType() == IN_CALL_SERVICE_TYPE_SYSTEM_UI);
  37. inCallService.addCall(parcelableCall);
  38. // Track the call if we don't already know about it.
  39. addCall(call);
  40. } catch (RemoteException ignored) {
  41. Log.e(this, ignored, "add call fialed");
  42. }
  43. }
  44. try {
  45. // 通知Call 相关状态的变化
  46. inCallService.onCallAudioStateChanged(mCallsManager.getAudioState());
  47. inCallService.onCanAddCallChanged(mCallsManager.canAddCall());
  48. } catch (RemoteException ignored) {
  49. Log.e(this, ignored, "changed event failed");
  50. }
  51. mBindingFuture.complete(true);
  52. Log.i(this, "%s calls sent to InCallService.", numCallsSent);
  53. Trace.endSection();
  54. return true;
  55. }

lnCallController 通过绑定服务的方式,开启拨号流程中的第二次跨进程访问,从Telecom 应用的system_serve进程再次回到Dialer应用的com.android .dialer 进程。

com.android.dialer 进程

InCallServiceImpl InCallService 的实现,负责和 Telecom 沟通,更新UI

Used to receive updates about calls from the Telecom component. This service is bound to Telecom while there exist calls which potentially require UI. This includes ringing (incoming), dialing (outgoing), and active calls. When the last call is disconnected, Telecom will unbind to the service triggering InCallActivity (via CallList) to finish soon after.

用于接收来自电信组件的有关呼叫的更新。当存在可能需要UI的调用时,此服务绑定到电信。这包括振铃(传入)、拨号(传出)和活动呼叫。当最后一个呼叫断开时,电信将解除与服务的绑定,并触发InCallActivity(通过CallList)在不久之后完成。

InCallServiceImpl 的核心功能 是在它的父类 InCallService, InCallServiceImpl 被绑定时,返回一个 InCallServiceBinder, 因此 system 进程拿到的接口就是这个, 绑定之前,会先初始化 InCallPresenter, InCallPresenter 是全局唯一(单例)的, 它负责 更新 电话APP的 UI。(MVP 模式)

  1. @Override
  2. public IBinder onBind(Intent intent) {
  3. Trace.beginSection("InCallServiceImpl.onBind");
  4. final Context context = getApplicationContext();
  5. final ContactInfoCache contactInfoCache = ContactInfoCache.getInstance(context);
  6. AudioModeProvider.getInstance().initializeAudioState(this);
  7. InCallPresenter.getInstance()
  8. .setUp(
  9. context,
  10. CallList.getInstance(),
  11. new ExternalCallList(),
  12. new StatusBarNotifier(context, contactInfoCache),
  13. new ExternalCallNotifier(context, contactInfoCache),
  14. contactInfoCache,
  15. new ProximitySensor(
  16. context, AudioModeProvider.getInstance(), new AccelerometerListener(context)),
  17. new FilteredNumberAsyncQueryHandler(context),
  18. speakEasyCallManager);
  19. InCallPresenter.getInstance().onServiceBind(); // 设置服务绑定状态mServiceBound 属性
  20. InCallPresenter.getInstance().maybeStartRevealAnimation(intent); // 开启Activity
  21. TelecomAdapter.getInstance().setInCallService(this);// 保存服务
  22. returnToCallController =
  23. new ReturnToCallController(this, ContactInfoCache.getInstance(context));
  24. feedbackListener = FeedbackComponent.get(context).getCallFeedbackListener();
  25. CallList.getInstance().addListener(feedbackListener);
  26. IBinder iBinder = super.onBind(intent); // 调用父类InCallService 的onBind 方法
  27. Trace.endSection();
  28. return iBinder;
  29. }
  1. @Override
  2. 421 public IBinder onBind(Intent intent) {
  3. 422 return new InCallServiceBinder();
  4. 423 }

转到 InCallServiceBinder

InCallServiceBinder 实现了IInCallService . aidl 的接口,这些接口通过发送Handler 消息, 将服务
接收到的服务请求转化为异步处理方式

  1. /** Manages the binder calls so that the implementor does not need to deal with it. */
  2. // InCallServiceBinder 实现了IInCallService . aidl 的接口,这些接口通过发送Handler 消息, 将服务
  3. //接收到的服务请求转化为异步处理方式
  4. private final class InCallServiceBinder extends IInCallService.Stub {
  5. @Override
  6. public void setInCallAdapter(IInCallAdapter inCallAdapter) {
  7. mHandler.obtainMessage(MSG_SET_IN_CALL_ADAPTER, inCallAdapter).sendToTarget();
  8. }
  9. @Override
  10. public void addCall(ParcelableCall call) {
  11. mHandler.obtainMessage(MSG_ADD_CALL, call).sendToTarget();
  12. }
  13. @Override
  14. public void updateCall(ParcelableCall call) {
  15. mHandler.obtainMessage(MSG_UPDATE_CALL, call).sendToTarget();
  16. }

mHandler 发送Handler 消息将llnCallService 的同步调用转换为异步处理,在后续的setlnCallAdapter  和  addCall 接口响应中继续分析其实现逻辑。

InCallPresenter MVP模式中, 控制逻辑和UI

InCallPresenter 的 maybeStartRevealAnimation 会启动 InCallActivity, 即 拨号进行中的界面(或者是来电界面)

  1. public void maybeStartRevealAnimation(Intent intent) {
  2. if (intent == null || inCallActivity != null) {
  3. return;
  4. }
  5. final Bundle extras = intent.getBundleExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS);
  6. if (extras == null) {
  7. // Incoming call, just show the in-call UI directly.
  8. return;
  9. }
  10. if (extras.containsKey(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS)) {
  11. // Account selection dialog will show up so don't show the animation.
  12. return;
  13. }
  14. final PhoneAccountHandle accountHandle =
  15. intent.getParcelableExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE);
  16. final Point touchPoint = extras.getParcelable(TouchPointManager.TOUCH_POINT);
  17. setBoundAndWaitingForOutgoingCall(true, accountHandle);
  18. if (shouldStartInBubbleModeWithExtras(extras)) {
  19. LogUtil.i("InCallPresenter.maybeStartRevealAnimation", "shouldStartInBubbleMode");
  20. // Show bubble instead of in call UI
  21. return;
  22. }
  23. final Intent activityIntent =
  24. InCallActivity.getIntent(context, false, true, false /* forFullScreen */);
  25. activityIntent.putExtra(TouchPointManager.TOUCH_POINT, touchPoint);
  26. context.startActivity(activityIntent);
  27. }

其中:getInCallIntent 就是创建一个启动 InCallActivity 的 Intent.

  1. public static Intent getIntent(
  2. Context context, boolean showDialpad, boolean newOutgoingCall, boolean isForFullScreen) {
  3. Intent intent = new Intent(Intent.ACTION_MAIN, null);
  4. intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_NEW_TASK);
  5. intent.setClass(context, InCallActivity.class);
  6. if (showDialpad) {
  7. intent.putExtra(IntentExtraNames.SHOW_DIALPAD, true);
  8. }
  9. intent.putExtra(IntentExtraNames.NEW_OUTGOING_CALL, newOutgoingCall);
  10. intent.putExtra(IntentExtraNames.FOR_FULL_SCREEN, isForFullScreen);
  11. return intent;
  12. }

至此, 拨号进行中的界面起来了, 接下来查看 InCallServiceBinder 里面的实现,setInCallAdapter 和 addCall。


链接:
 

InCallServiceBinder 收到消息,是直接转交给 mHandler  

  1. /** Manages the binder calls so that the implementor does not need to deal with it. */
  2. private final class InCallServiceBinder extends IInCallService.Stub {
  3. @Override
  4. public void setInCallAdapter(IInCallAdapter inCallAdapter) {
  5. mHandler.obtainMessage(MSG_SET_IN_CALL_ADAPTER, inCallAdapter).sendToTarget();
  6. }
  7. @Override
  8. public void addCall(ParcelableCall call) {
  9. mHandler.obtainMessage(MSG_ADD_CALL, call).sendToTarget();
  10. }

看一下 mHandler 对象,在 case MSG_SET_IN_CALL_ADAPTER 中创建了 Phone 对象

Phone 在UI层面上, Phone是唯一的,不分类型,而且数量只有一个

  1. private final Handler mHandler = new Handler(Looper.getMainLooper()) {
  2. @Override
  3. public void handleMessage(Message msg) {
  4. // ...
  5. switch (msg.what) {
  6. case MSG_SET_IN_CALL_ADAPTER:
  7. // setInCallAdapter 触发创建 com.android.dialer 的唯一 的phone对象
  8. // 也就是说, 在 com.android.dialer 进程的所有操作 都是经过 phone 里面的mInCallAdapter 发送到 system 进程的 (框架层)
  9. mPhone = new Phone(new InCallAdapter((IInCallAdapter) msg.obj));
  10. // 核心, 让InCallService 监听 Phone 的状态变化
  11. mPhone.addListener(mPhoneListener);
  12. onPhoneCreated(mPhone);
  13. break;
  14. case MSG_ADD_CALL:
  15. mPhone.internalAddCall((ParcelableCall) msg.obj);
  16. break;
  17. case MSG_UPDATE_CALL:
  18. mPhone.internalUpdateCall((ParcelableCall) msg.obj);
  19. break;
  20. // ...
  21. // 省略大量消息类型
  22. }
  23. }

mPhone.internalAddCall 创建一个本地的Telecom Call (不同于system进程的Call, 下面简称TCall),通知 InCallService

  1. final void internalAddCall(ParcelableCall parcelableCall) {
  2. Call call = new Call(this, parcelableCall.getId(), mInCallAdapter,
  3. parcelableCall.getState());
  4. mCallByTelecomCallId.put(parcelableCall.getId(), call);
  5. mCalls.add(call);
  6. checkCallTree(parcelableCall);
  7. call.internalUpdate(parcelableCall, mCallByTelecomCallId);
  8. // 核心, 通知 InCallService 有添加了一个Call
  9. //private void fireCallAdded(Call call) {
  10. // for (Listener listener : mListeners) {
  11. // listener.onCallAdded(this, call);
  12. // }
  13. //}
  14. fireCallAdded(call);
  15. }

其中的 fireCallAdded方法中的 mListeners 如下表示

这其实是个空实现,具体实现是在子类中,继续跟进到子类 InCallServiceImpl  中分析

  1. private Phone.Listener mPhoneListener = new Phone.Listener() {
  2. /** ${inheritDoc} */
  3. @Override
  4. public void onAudioStateChanged(Phone phone, AudioState audioState) {
  5. InCallService.this.onAudioStateChanged(audioState);
  6. }
  7. 。。。。。//
  8. /** ${inheritDoc} */
  9. @Override
  10. public void onCallAdded(Phone phone, Call call) {
  11. InCallService.this.onCallAdded(call);
  12. }

 

mPhoneListener.onCallAdded => InCallServiceImpl.onCallAdded

  1. public void onCallAdded(Call call) {
  2. // 核心, 主过程
  3. //CallList.getInstance().onCallAdded(call);
  4. // 绑定监听 TCall 的状态变化
  5. InCallPresenter.getInstance().onCallAdded(call);
  6. }
  1. public void onCallAdded(final android.telecom.Call call) {
  2. LatencyReport latencyReport = new LatencyReport(call);
  3. if (shouldAttemptBlocking(call)) {
  4. maybeBlockCall(call, latencyReport);
  5. } else {
  6. if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
  7. mExternalCallList.onCallAdded(call);
  8. } else {
  9. latencyReport.onCallBlockingDone();
  10. //CallList(Call的维护列表)调用onCallAdded
  11. mCallList.onCallAdded(mContext, call, latencyReport);
  12. }
  13. }
  14. // Since a call has been added we are no longer waiting for Telecom to send us a call.
  15. setBoundAndWaitingForOutgoingCall(false, null);
  16. call.registerCallback(mCallCallback);
  17. }
  1. 129 public void onCallAdded(
  2. 130 final Context context, final android.telecom.Call telecomCall, LatencyReport latencyReport) {
  3. 131 Trace.beginSection("CallList.onCallAdded");
  4. 216 if (call.getState() == DialerCallState.INCOMING
  5. 217 || call.getState() == DialerCallState.CALL_WAITING) {
  6. 218 if (call.isActiveRttCall()) {
  7. 219 if (!call.isPhoneAccountRttCapable()) {
  8. 220 RttPromotion.setEnabled(context);
  9. 221 }
  10. 222 Logger.get(context)
  11. 223 .logCallImpression(
  12. 224 DialerImpression.Type.INCOMING_RTT_CALL,
  13. 225 call.getUniqueCallId(),
  14. 226 call.getTimeAddedMs());
  15. 227 }
  16. // 来电进行处理
  17. 228 onIncoming(call);
  18. 229 } else {
  19. // 对拨号进行处理
  20. 230 if (call.isActiveRttCall()) {
  21. 231 Logger.get(context)
  22. 232 .logCallImpression(
  23. 233 DialerImpression.Type.OUTGOING_RTT_CALL,
  24. 234 call.getUniqueCallId(),
  25. 235 call.getTimeAddedMs());
  26. 236 }
  27. 237 onUpdateCall(call);
  28. // 核心代码
  29. 238 notifyGenericListeners();

CallList 维护电话列表

CallList维护着一个打电话列表 (CallList里面的Call简称为 LCall, 区别于上面的 TCall), 每一个 LCall 维护着一个 TCall.

  • TCall 是由 Phone 维护的
  • LCall 是由 CallList 维护的
  • TCall 和 LCall 一一对应

继续跟踪 notifyGenericListeners 方法

  1. 633 private void notifyGenericListeners() {
  2. 634 Trace.beginSection("CallList.notifyGenericListeners");
  3. 635 for (Listener listener : listeners) {
  4. 636 listener.onCallListChange(this);
  5. 637 }
  6. 638 Trace.endSection();
  7. 639 }

跟踪 监听者 listeners

下面查找谁监听了 CallListInCallPresenter 实现了 CallList.Listener 接口, 所以 InCallPresenter.onCallListChange 会被触发

public class InCallPresenter implements CallList.Listener, AudioModeProvider.AudioModeListener {

 跟踪到 onCallListChange 方法

  1. public void onCallListChange(CallList callList) {
  2. // ...
  3. // 根据新状态,决定是否打开 InCallActivity, 或则关闭 InCallActivity, 确保不会重复打开
  4. newState = startOrFinishUi(newState);
  5. for (InCallStateListener listener : mListeners) {
  6. // 凡是监听 InCallPresenter 的监听者,都得到通知。
  7. listener.onStateChange(oldState, mInCallState, callList);
  8. }
  9. }

上述涉及到 InCallStateListener  监听者,是一个接口,它定义了一个方法onStateChange

再谈 InCallActivity

InCallActivity 展示拨号,或者来电状态

InCallActivity 是通过 展示 或隐藏 Fragment 来 区分不同状态的, 拨号进行中的Fragment 是 DialpadFragment , 而 DialpadFragment 对应的 Presenter 是 DialpadPresenter, onUiReady

InCallPresenter.java直接控制着InCallActivity,与此同时,通过一些监听器,例如IncomingCallListener/ CanAddCallListener/ InCallDetailsListener等 控制着AnswerPresenter等等。

AnswerPresenter控制着AnswerFragment的显示,是InCallActivity界面的一部分;

VideoCallPresenter控制着VideoCallFragment的显示,是InCallActivity界面的一部分;

CallCardPresenter控制着CallCardFragment的显示,是InCallActivity界面的一部分;

CallButtonPresenter控制着CallButtonFragment的显示,是InCallActivity界面的一部分;

这些Presenter一般会实现InCallPresenter的监听器对应的方法。

其中:

CallCardFragment:用于显示联系人信息及通话时间等;
CallButtonFragment:通话界面下方的控制按钮。
DialpadFragment:拨号盘显示控件。
AnswerFragment:来电控制控件,用于操作接听/拒接/短信快捷回复。
ConferenceManagerFragment:会议电话的界面。
VideoCallFragment:视屏通话控件,在CallCardFragment中调用。

如下

  1. public void onUiReady(DialpadUi ui) {
  2. super.onUiReady(ui);
  3. InCallPresenter.getInstance().addListener(this);
  4. call = CallList.getInstance().getOutgoingOrActive();
  5. }

所以 DialpadFragment .onStateChange 会被触发 接着就是更新UI了(MVP)

  1. private static final Map<Integer, Character> displayMap = new ArrayMap<>();
  2. /** Set up the static maps */
  3. static {
  4. // Map the buttons to the display characters
  5. displayMap.put(R.id.one, '1');
  6. displayMap.put(R.id.two, '2');
  7. displayMap.put(R.id.three, '3');
  8. displayMap.put(R.id.four, '4');
  9. displayMap.put(R.id.five, '5');
  10. displayMap.put(R.id.six, '6');
  11. displayMap.put(R.id.seven, '7');
  12. displayMap.put(R.id.eight, '8');
  13. displayMap.put(R.id.nine, '9');
  14. displayMap.put(R.id.zero, '0');
  15. displayMap.put(R.id.pound, '#');
  16. displayMap.put(R.id.star, '*');
  17. }

 

总结一下: system 进程的 InCallController 收到来自于 CallsManager 的消息后, 发送到 com.android.dialer 进程, 一步步地更新 拨号界面的状态, 整个过程已经全部打通了。

第二个分支:CallsManager.placeOutgoingCall

执行 broadcaster. processCall () 方法

  1. public void processCall(CallDisposition disposition) {
  2. if (disposition.callImmediately) {
  3. boolean speakerphoneOn = mIntent.getBooleanExtra(
  4. TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, false);
  5. int videoState = mIntent.getIntExtra(
  6. TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE,
  7. VideoProfile.STATE_AUDIO_ONLY);
  8. placeOutgoingCallImmediately(mCall, disposition.callingAddress, null,
  9. speakerphoneOn, videoState);

其中的  placeOutgoingCallImmediately 方法

  1. private void placeOutgoingCallImmediately(Call call, Uri handle, GatewayInfo gatewayInfo,
  2. boolean speakerphoneOn, int videoState) {
  3. Log.i(this,
  4. "Placing call immediately instead of waiting for OutgoingCallBroadcastReceiver");
  5. // Since we are not going to go through "Outgoing call broadcast", make sure
  6. // we mark it as ready.
  7. mCall.setNewOutgoingCallIntentBroadcastIsDone();
  8. mCallsManager.placeOutgoingCall(call, handle, gatewayInfo, speakerphoneOn, videoState);
  9. }

CallsManager.placeOutgoingCall

  1. 2048 @VisibleForTesting
  2. 2049 public void placeOutgoingCall(Call call, Uri handle, GatewayInfo gatewayInfo,
  3. 2050 boolean speakerphoneOn, int videoState) {
  4. 2051 if (call == null) {
  5. 2052 // don't do anything if the call no longer exists
  6. 2053 Log.i(this, "Canceling unknown call.");
  7. 2054 return;
  8. 2055 }
  9. 2056
  10. 2057 final Uri uriHandle = (gatewayInfo == null) ? handle : gatewayInfo.getGatewayAddress();
  11. 2058
  12. 2059 if (gatewayInfo == null) {
  13. 2060 Log.i(this, "Creating a new outgoing call with handle: %s", Log.piiHandle(uriHandle));
  14. 2061 } else {
  15. 2062 Log.i(this, "Creating a new outgoing call with gateway handle: %s, original handle: %s",
  16. 2063 Log.pii(uriHandle), Log.pii(handle));
  17. 2064 }
  18. 2065
  19. 2066 call.setHandle(uriHandle);
  20. 2067 call.setGatewayInfo(gatewayInfo);
  21. 2068
  22. 2069 final boolean useSpeakerWhenDocked = mContext.getResources().getBoolean(
  23. 2070 R.bool.use_speaker_when_docked);
  24. 2071 final boolean useSpeakerForDock = isSpeakerphoneEnabledForDock();
  25. 2072 final boolean useSpeakerForVideoCall = isSpeakerphoneAutoEnabledForVideoCalls(videoState);
  26. 2073
  27. 2074 // Auto-enable speakerphone if the originating intent specified to do so, if the call
  28. 2075 // is a video call, of if using speaker when docked
  29. 2076 call.setStartWithSpeakerphoneOn(speakerphoneOn || useSpeakerForVideoCall
  30. 2077 || (useSpeakerWhenDocked && useSpeakerForDock));
  31. 2078 call.setVideoState(videoState);
  32. 2079
  33. 2080 if (speakerphoneOn) {
  34. 2081 Log.i(this, "%s Starting with speakerphone as requested", call);
  35. 2082 } else if (useSpeakerWhenDocked && useSpeakerForDock) {
  36. 2083 Log.i(this, "%s Starting with speakerphone because car is docked.", call);
  37. 2084 } else if (useSpeakerForVideoCall) {
  38. 2085 mInVideoMode = true; // UNISOC: add for bug1152803
  39. 2086 Log.i(this, "%s Starting with speakerphone because its a video call.", call);
  40. 2087 }
  41. 2088
  42. 2089 if (call.isEmergencyCall()) {
  43. 2090 new AsyncEmergencyContactNotifier(mContext).execute();
  44. 2091 }
  45. 2092
  46. 2093 final boolean requireCallCapableAccountByHandle = mContext.getResources().getBoolean(
  47. 2094 com.android.internal.R.bool.config_requireCallCapableAccountForHandle);
  48. 2095 final boolean isOutgoingCallPermitted = isOutgoingCallPermitted(call,
  49. 2096 call.getTargetPhoneAccount());
  50. 2097 final String callHandleScheme =
  51. 2098 call.getHandle() == null ? null : call.getHandle().getScheme();
  52. 2099 if (call.getTargetPhoneAccount() != null || call.isEmergencyCall()) {
  53. 2100 // If the account has been set, proceed to place the outgoing call.
  54. 2101 // Otherwise the connection will be initiated when the account is set by the user.
  55. 2102 if (call.isSelfManaged() && !isOutgoingCallPermitted) {
  56. 2103 notifyCreateConnectionFailed(call.getTargetPhoneAccount(), call);
  57. 2104 } else {
  58. 2105 if (call.isEmergencyCall()) {
  59. 2106 // Drop any ongoing self-managed calls to make way for an emergency call.
  60. 2107 disconnectSelfManagedCalls("place emerg call" /* reason */);
  61. 2108 }
  62. 2109
  63. 2110 call.startCreateConnection(mPhoneAccountRegistrar);
  64. 2111 }
  65. 2112 } else if (mPhoneAccountRegistrar.getCallCapablePhoneAccounts(
  66. 2113 requireCallCapableAccountByHandle ? callHandleScheme : null, false,
  67. 2114 call.getInitiatingUser()).isEmpty()) {
  68. 2115 // If there are no call capable accounts, disconnect the call.
  69. 2116 markCallAsDisconnected(call, new DisconnectCause(DisconnectCause.CANCELED,
  70. 2117 "No registered PhoneAccounts"));
  71. 2118 markCallAsRemoved(call);
  72. 2119 }
  73. 2120 }

Call 由 CallsManager 维护的拨号,或者来电实例

Call.startCreateConnection

  1. void startCreateConnection(PhoneAccountRegistrar phoneAccountRegistrar) {
  2. if (mCreateConnectionProcessor != null) {
  3. Log.w(this, "mCreateConnectionProcessor in startCreateConnection is not null. This is" +
  4. " due to a race between NewOutgoingCallIntentBroadcaster and " +
  5. "phoneAccountSelected, but is harmlessly resolved by ignoring the second " +
  6. "invocation.");
  7. return;
  8. }
  9. mCreateConnectionProcessor = new CreateConnectionProcessor(this, mRepository, this,
  10. phoneAccountRegistrar, mContext);
  11. mCreateConnectionProcessor.process();
  12. }

CreateConnectionProcessor.process ==> CreateConnectionProcessor.attemptNextPhoneAccount

  1. @VisibleForTesting
  2. public void process() {
  3. Log.v(this, "process");
  4. clearTimeout();
  5. mAttemptRecords = new ArrayList<>();
  6. if (mCall.getTargetPhoneAccount() != null) {
  7. mAttemptRecords.add(new CallAttemptRecord(
  8. mCall.getTargetPhoneAccount(), mCall.getTargetPhoneAccount()));
  9. }
  10. if (!mCall.isSelfManaged()) {
  11. adjustAttemptsForConnectionManager();
  12. adjustAttemptsForEmergency(mCall.getTargetPhoneAccount());
  13. }
  14. mAttemptRecordIterator = mAttemptRecords.iterator();
  15. attemptNextPhoneAccount();
  16. }

attemptNextPhoneAccount 方法

  1. private ConnectionServiceWrapper mService;
  2. private void attemptNextPhoneAccount() {
  3. //。。。//
  4. if (mCallResponse != null && attempt != null) {
  5. Log.i(this, "Trying attempt %s", attempt);
  6. PhoneAccountHandle phoneAccount = attempt.connectionManagerPhoneAccount;
  7. mService = mRepository.getService(phoneAccount.getComponentName(),
  8. phoneAccount.getUserHandle());
  9. if (mService == null) {
  10. Log.i(this, "Found no connection service for attempt %s", attempt);
  11. attemptNextPhoneAccount();
  12. } else {
  13. mConnectionAttempt++;
  14. mCall.setConnectionManagerPhoneAccount(attempt.connectionManagerPhoneAccount);
  15. mCall.setTargetPhoneAccount(attempt.targetPhoneAccount);
  16. mCall.setConnectionService(mService);
  17. setTimeoutIfNeeded(mService, attempt);
  18. if (mCall.isIncoming()) {
  19. mService.createConnection(mCall, CreateConnectionProcessor.this);
  20. } else {
  21. // Start to create the connection for outgoing call after the ConnectionService
  22. // of the call has gained the focus.
  23. mCall.getConnectionServiceFocusManager().requestFocus(
  24. mCall,
  25. new CallsManager.RequestCallback(new CallsManager.PendingAction() {
  26. @Override
  27. public void performAction() {
  28. Log.d(this, "perform create connection");
  29. mService.createConnection(
  30. mCall,
  31. CreateConnectionProcessor.this);
  32. }
  33. }));
  34. }
  35. }
  36. } else {
  37. Log.v(this, "attemptNextPhoneAccount, no more accounts, failing");
  38. DisconnectCause disconnectCause = mLastErrorDisconnectCause != null ?
  39. mLastErrorDisconnectCause : new DisconnectCause(DisconnectCause.ERROR);
  40. notifyCallConnectionFailure(disconnectCause);
  41. }

ConnectionServiceWrapper 负责和 Telephony 沟通

mService.createConnection(mCall, CreateConnectionProcessor.this); 开始进行链接

  1. void createConnection(final Call call, final CreateConnectionResponse response) {
  2. // 链接创建成功后 onSuccess 会被调用
  3. BindCallback callback = new BindCallback() {
  4. @Override
  5. public void onSuccess() {
  6. try {
  7. /// M: For VoLTE @{
  8. boolean isConferenceDial = call.isConferenceDial();
  9. // 会议通话
  10. if (isConferenceDial) {
  11. logOutgoing("createConference(%s) via %s.", call, getComponentName());
  12. mServiceInterface.createConference(
  13. call.getConnectionManagerPhoneAccount(),
  14. callId,
  15. new ConnectionRequest(
  16. call.getTargetPhoneAccount(),
  17. call.getHandle(),
  18. extras,
  19. call.getVideoState()),
  20. call.getConferenceParticipants(),
  21. call.isIncoming());
  22. // 非会议(拨打电话会走这里)
  23. } else {
  24. // 通过远程接口创建链接
  25. mServiceInterface.createConnection(
  26. call.getConnectionManagerPhoneAccount(),
  27. callId,
  28. new ConnectionRequest(
  29. call.getTargetPhoneAccount(),
  30. call.getHandle(),
  31. extras,
  32. call.getVideoState()),
  33. call.isIncoming(),
  34. call.isUnknown());
  35. }
  36. /// @}
  37. } catch (RemoteException e) {
  38. }
  39. }
  40. @Override
  41. public void onFailure() {
  42. }
  43. };
  44. mBinder.bind(callback, call);
  45. }

mBinder是Binder2对象,Binder2是ConnectionServiceWrapper的父类ServiceBinder内部类,所以此处调用的是的ServiceBinder的内部类的Binder2类的bind()方法,先new一个ServiceConnection对象,然后绑定一个远程服务端服务。

 

如果绑定成功的话,在ServiceBinder的内部类ServiceBinderConnection的onServiceConnected()方法就被调用。
在这里做了两件事:

       1).通过setBinder()方法,回调ConnectionServiceWrapper的setServiceInterface()方法,通过mServiceInterface = IConnectionService.Stub.asInterface(binder);
这行代码获取一个远程服务端的对象mServiceInterface 。
  2).再通过调用handleSuccessfulConnection()方法回调callback 的onSuccess()方法,也就又回到ConnectionServiceWrapper的createConnection()方法里。调用ConnectionService.java里mBinder的createConnection()方法然后通过message传递调用createConnection()方法。

mBider 的bind 方法

  1. void bind(BindCallback callback, Call call) {
  2. if (mServiceConnection == null) {
  3. Intent serviceIntent = new Intent(mServiceAction).setComponent(mComponentName);
  4. ServiceConnection connection = new ServiceBinderConnection(call);
  5. // 进行绑定
  6. if (mUserHandle != null) {
  7. isBound = mContext.bindServiceAsUser(serviceIntent, connection, bindingFlags,
  8. mUserHandle);
  9. } else {
  10. isBound = mContext.bindService(serviceIntent, connection, bindingFlags);
  11. }
  12. if (!isBound) {
  13. handleFailedConnection();
  14. return;
  15. }
  16. } else {
  17. }
  18. }

绑定成功后,ServiceBinderConnection 的 onServiceConnected 会触发

  1. @Override
  2. public void onServiceConnected(ComponentName componentName, IBinder binder) {
  3. try {
  4. if (binder != null) {
  5. mServiceDeathRecipient = new ServiceDeathRecipient(componentName);
  6. try {
  7. binder.linkToDeath(mServiceDeathRecipient, 0);
  8. mServiceConnection = this;
  9. // 会触发 ConnectionServiceWrapper.setServiceInterface ==>
  10. ConnectionServiceWrapper.addConnectionServiceAdapter
  11. 通过mServiceInterface,给绑定的服务,提供一个访问自己的接口
  12. setBinder(binder);
  13. // 触发bind(BindCallback callback, Call call) 中 callback 的 onSuccess
  14. handleSuccessfulConnection();
  15. } catch (RemoteException e) {
  16. Log.w(this, "onServiceConnected: %s died.");
  17. if (mServiceDeathRecipient != null) {
  18. mServiceDeathRecipient.binderDied();
  19. }
  20. }
  21. }
  22. }
  23. } finally {
  24. Log.endSession();
  25. }
  26. }

整个绑定过程,只做2件事,

一是给远程服务提供访问自己的接口,

二是利用远程接口创建一个通话链接。

这2件事都是跨进程进行的。远程服务访问自己的接口是 ConnectionServiceWrapper.Adapter , 是一个Binder。

ConnectionServiceWrapper.Adapter 提供了一套更新Call 状态的 操作, 因为目前分析的是拨打电话流程,所以先分析setDialing

由内部类 Adapter 继承于 IConnectionServiceAdapter.Stub,可以看出会进行跨进程访问

  1. public class ConnectionServiceWrapper extends ServiceBinder implements
  2. ConnectionServiceFocusManager.ConnectionServiceFocus {
  3. private final class Adapter extends IConnectionServiceAdapter.Stub {

 

调用ConnectionService.java里mBinder的createConnection()方法然后通过message传递调用createConnection()方法。

  1. private void handleSuccessfulConnection() {
  2. // Make a copy so that we don't have a deadlock inside one of the callbacks.
  3. Set<BindCallback> callbacksCopy = new ArraySet<>();
  4. synchronized (mCallbacks) {
  5. callbacksCopy.addAll(mCallbacks);
  6. mCallbacks.clear();
  7. }
  8. for (BindCallback callback : callbacksCopy) {
  9. callback.onSuccess();
  10. }
  11. }

通过调用handleSuccessfulConnection()方法回调callback 的onSuccess()方法,也就又回到ConnectionServiceWrapper的createConnection()方法里。

  1. 1094 public void createConnection(final Call call, final CreateConnectionResponse response) {
  2. 1095 Log.d(this, "createConnection(%s) via %s.", call, getComponentName());
  3. 1096 BindCallback callback = new BindCallback() {
  4. 1097 @Override
  5. 1098 public void onSuccess() {
  6. 1099 String callId = mCallIdMapper.getCallId(call);
  7. 1100 mPendingResponses.put(callId, response);
  8. 1101
  9. ///---------//
  10. 1146
  11. 1150 // 核心代码
  12. 1151 try {
  13. 1152 mServiceInterface.createConnection(
  14. 1153 call.getConnectionManagerPhoneAccount(),
  15. 1154 callId,
  16. 1155 connectionRequest,
  17. 1156 call.shouldAttachToExistingConnection(),
  18. 1157 call.isUnknown(),
  19. 1158 Log.getExternalSession());
  20. 1159
  21. 1160 } catch (RemoteException e) {
  22. 1161 Log.e(this, e, "Failure to createConnection -- %s", getComponentName());
  23. 1162 mPendingResponses.remove(callId).handleCreateConnectionFailure(
  24. 1163 new DisconnectCause(DisconnectCause.ERROR, e.toString()));
  25. 1164 }
  26. 1165 }
  27. 1166
  28. 1167 @Override
  29. 1168 public void onFailure() {
  30. 1169 Log.e(this, new Exception(), "Failure to call %s", getComponentName());
  31. 1170 response.handleCreateConnectionFailure(new DisconnectCause(DisconnectCause.ERROR));
  32. 1171 }
  33. 1172 };
  34. 1173
  35. 1174 mBinder.bind(callback, call);
  36. 1175 }
private IConnectionService mServiceInterface;

 

createConnection()方法通过判断是来电还是去电分别创建不同的connection,

去电则调用onCreateOutgoingConnection(),

TelephonyConnectionService是ConnectionService的实例,所以进入TelephonyConnectionService.java的onCreateOutgoingConnection()方法。

 

  1. private void createConnection(
  2. final PhoneAccountHandle callManagerAccount,
  3. final String callId,
  4. final ConnectionRequest request,
  5. boolean isIncoming,
  6. boolean isUnknown) {
  7. boolean isLegacyHandover = request.getExtras() != null &&
  8. request.getExtras().getBoolean(TelecomManager.EXTRA_IS_HANDOVER, false);
  9. boolean isHandover = request.getExtras() != null && request.getExtras().getBoolean(
  10. TelecomManager.EXTRA_IS_HANDOVER_CONNECTION, false);
  11. Log.d(this, "createConnection, callManagerAccount: %s, callId: %s, request: %s, " +
  12. "isIncoming: %b, isUnknown: %b, isLegacyHandover: %b, isHandover: %b",
  13. callManagerAccount, callId, request, isIncoming, isUnknown, isLegacyHandover,
  14. isHandover);
  15. Connection connection = null;
  16. if (isHandover) {
  17. PhoneAccountHandle fromPhoneAccountHandle = request.getExtras() != null
  18. ? (PhoneAccountHandle) request.getExtras().getParcelable(
  19. TelecomManager.EXTRA_HANDOVER_FROM_PHONE_ACCOUNT) : null;
  20. if (!isIncoming) {
  21. connection = onCreateOutgoingHandoverConnection(fromPhoneAccountHandle, request);
  22. } else {
  23. connection = onCreateIncomingHandoverConnection(fromPhoneAccountHandle, request);
  24. }
  25. } else {
  26. connection = isUnknown ? onCreateUnknownConnection(callManagerAccount, request)
  27. : isIncoming ? onCreateIncomingConnection(callManagerAccount, request)
  28. : onCreateOutgoingConnection(callManagerAccount, request);
  29. }

 

TelephonyConnectionService是ConnectionService的实例,所以进入TelephonyConnectionService.java的onCreateOutgoingConnection()方法。 

  1. @Override
  2. public Connection onCreateOutgoingConnection(
  3. PhoneAccountHandle connectionManagerPhoneAccount,
  4. final ConnectionRequest request) {
  5. //这里做了很多判断,返回失败的连接(比如拨打号码为空,未指定sim卡,设置为仅4G等)
  6. ......
  7. // Get the right phone object from the account data passed in.
  8. final Phone phone = getPhoneForAccount(request.getAccountHandle(), isEmergencyNumber,
  9. /* Note: when not an emergency, handle can be null for unknown callers */
  10. handle == null ? null : handle.getSchemeSpecificPart());
  11. if (!isEmergencyNumber) {
  12. final Connection resultConnection = getTelephonyConnection(request, numberToDial,
  13. false, handle, phone);
  14. return placeOutgoingConnection(request, resultConnection, phone);
  15. } else {
  16. final Connection resultConnection = getTelephonyConnection(request, numberToDial,
  17. true, handle, phone);
  18. CompletableFuture<Boolean> phoneFuture = delayDialForDdsSwitch(phone);
  19. phoneFuture.whenComplete((result, error) -> {
  20. if (error != null) {
  21. Log.w(this, "onCreateOutgoingConn - delayDialForDdsSwitch exception= "
  22. + error.getMessage());
  23. }
  24. Log.i(this, "onCreateOutgoingConn - delayDialForDdsSwitch result = " + result);
  25. placeOutgoingConnection(request, resultConnection, phone);
  26. });
  27. return resultConnection;
  28. }
  29. ......
  30. //如果上面的都不是则执行这里
  31. placeOutgoingConnection(connection, phone, request);
  32. }

继续跟踪placeOutgoingConnection()方法处理拨号流程
 

  1. private void placeOutgoingConnection(
  2. TelephonyConnection connection, Phone phone, ConnectionRequest request) {
  3. placeOutgoingConnection(connection, phone, request.getVideoState(), request.getExtras());
  4. }

又进入到另外一个 placeOutgoingConnection() 方法中

  1. private void placeOutgoingConnection(
  2. TelephonyConnection connection, Phone phone, int videoState, Bundle extras) {
  3. String number = connection.getAddress().getSchemeSpecificPart();
  4. boolean isAddParticipant = (extras != null) && extras
  5. .getBoolean(TelephonyProperties.ADD_PARTICIPANT_KEY, false);
  6. Log.d(this, "placeOutgoingConnection isAddParticipant = " + isAddParticipant);
  7. updatePhoneAccount(connection, phone);
  8. com.android.internal.telephony.Connection originalConnection = null;
  9. try {
  10. if (phone != null) {
  11. if (isAddParticipant) {
  12. phone.addParticipant(number);// 为紧急号码做一些处理
  13. return;
  14. } else {
  15. // 核心代码
  16. originalConnection = phone.dial(number, new ImsPhone.ImsDialArgs.Builder() //呼叫
  17. .setVideoState(videoState)
  18. .setIntentExtras(extras)
  19. .setRttTextStream(connection.getRttTextStream())
  20. .build());
  21. }
  22. }
  23. } catch (CallStateException e) { // 失败处理
  24. Log.e(this, e, "placeOutgoingConnection, phone.dial exception: " + e);
  25. int cause = android.telephony.DisconnectCause.OUTGOING_FAILURE;
  26. if (e.getError() == CallStateException.ERROR_OUT_OF_SERVICE) {
  27. cause = android.telephony.DisconnectCause.OUT_OF_SERVICE;
  28. } else if (e.getError() == CallStateException.ERROR_POWER_OFF) {
  29. cause = android.telephony.DisconnectCause.POWER_OFF;
  30. }
  31. connection.setDisconnected(DisconnectCauseUtil.toTelecomDisconnectCause(
  32. cause, e.getMessage(), phone.getPhoneId()));
  33. connection.clearOriginalConnection();
  34. connection.destroy();
  35. return;
  36. }
  37. if (originalConnection == null) { // 失败处理
  38. int telephonyDisconnectCause = android.telephony.DisconnectCause.OUTGOING_FAILURE;
  39. // On GSM phones, null connection means that we dialed an MMI code
  40. if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_GSM) {
  41. Log.d(this, "dialed MMI code");
  42. int subId = phone.getSubId();
  43. Log.d(this, "subId: "+subId);
  44. telephonyDisconnectCause = android.telephony.DisconnectCause.DIALED_MMI;
  45. final Intent intent = new Intent(this, MMIDialogActivity.class);
  46. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
  47. Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  48. if (SubscriptionManager.isValidSubscriptionId(subId)) {
  49. intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
  50. }
  51. startActivity(intent);
  52. }
  53. Log.d(this, "placeOutgoingConnection, phone.dial returned null");
  54. connection.setDisconnected(DisconnectCauseUtil.toTelecomDisconnectCause(
  55. telephonyDisconnectCause, "Connection is null", phone.getPhoneId()));
  56. connection.clearOriginalConnection();
  57. connection.destroy();
  58. } else {
  59. connection.setOriginalConnection(originalConnection); // TelephonyConnection 监听 phone, 更新时,从originalConnection里面取。
  60. //TelephonyConnection.setOriginalConnection 的实现, 目的主要是为将 mHandler 注册注册到
  61. //phone 的监听者列表里面, phone 变化, 会触发 mHandler 里面的handleMessage 被调用。
  62. }

调用Phone的dial()方法后就进入了Telephony Framework层了。Android 7.0中把GSMPhone和CDMAPhone全部集成到GsmCdmaPhone中,继续看GsmCdmaPhone中dial()

  1. @Override
  2. public Connection dial(String dialString, UUSInfo uusInfo, int videoState, Bundle intentExtras)
  3. throws CallStateException {
  4. .......
  5. //ImsPhone是专门处理VoLTE的一个类
  6. if (videoState == VideoProfile.STATE_AUDIO_ONLY) {
  7. if (DBG) Rlog.d(LOG_TAG, "Trying IMS PS call");//
  8. return imsPhone.dial(dialString, uusInfo, videoState, intentExtras);
  9. } else {
  10. if (SystemProperties.get("persist.mtk_vilte_support").equals("1")) {
  11. //支持VoLTe Ims ps video call
  12. return imsPhone.dial(dialString, uusInfo, videoState, intentExtras);
  13. } else {
  14. //cs video call
  15. return dialInternal(dialString, uusInfo, videoState, intentExtras);
  16. /// @}
  17. }
  18. .......
  19. if (isPhoneTypeGsm()) {
  20. /// M: CC: For 3G VT only @{
  21. //return dialInternal(dialString, null, VideoProfile.STATE_AUDIO_ONLY, intentExtras);
  22. return dialInternal(dialString, null, videoState, intentExtras);
  23. /// @}
  24. } else {
  25. return dialInternal(dialString, null, videoState, intentExtras);
  26. }
  27. }

继续看dialInternal() 方法,这里有 2 个

  1. @Override
  2. protected Connection dialInternal(String dialString, DialArgs dialArgs)
  3. throws CallStateException {
  4. return dialInternal(dialString, dialArgs, null);
  5. }
  6. protected Connection dialInternal(String dialString, DialArgs dialArgs,
  7. ResultReceiver wrappedCallback)
  8. throws CallStateException {
  9. // Need to make sure dialString gets parsed properly
  10. String newDialString = PhoneNumberUtils.stripSeparators(dialString);
  11. if (isPhoneTypeGsm()) {
  12. // handle in-call MMI first if applicable
  13. if (handleInCallMmiCommands(newDialString)) {
  14. return null;
  15. }
  16. // Only look at the Network portion for mmi
  17. String networkPortion = PhoneNumberUtils.extractNetworkPortionAlt(newDialString);
  18. GsmMmiCode mmi = GsmMmiCode.newFromDialString(networkPortion, this,
  19. mUiccApplication.get(), wrappedCallback);
  20. if (DBG) logd("dialInternal: dialing w/ mmi '" + mmi + "'...");
  21. if (mmi == null) {
  22. return mCT.dialGsm(newDialString, dialArgs.uusInfo, dialArgs.intentExtras);
  23. } else if (mmi.isTemporaryModeCLIR()) {
  24. return mCT.dialGsm(mmi.mDialingNumber, mmi.getCLIRMode(), dialArgs.uusInfo,
  25. dialArgs.intentExtras);
  26. } else {
  27. mPendingMMIs.add(mmi);
  28. mMmiRegistrants.notifyRegistrants(new AsyncResult(null, mmi, null));
  29. mmi.processCode();
  30. return null;
  31. }
  32. } else {
  33. // 核心方法
  34. return mCT.dial(newDialString, dialArgs.intentExtras);
  35. }
  36. }

mCT是GsmCdmaCallTracker对象,我们接着看GsmCdmaCallTracker中的dial()

依据不同制式 拨打电话 

  1. public Connection dial(String dialString, Bundle intentExtras) throws CallStateException {
  2. if (isPhoneTypeGsm()) {
  3. return dialGsm(dialString, CommandsInterface.CLIR_DEFAULT, intentExtras);
  4. } else {
  5. return dialCdma(dialString, CommandsInterface.CLIR_DEFAULT, intentExtras);
  6. }
  7. }

继续跟踪 diaCdma 代码

  1. 315 public synchronized Connection dialGsm(String dialString, int clirMode, UUSInfo uusInfo,
  2. 316 Bundle intentExtras)
  3. 317 throws CallStateException {
  4. 369
  5. 370
  6. 371 if ( mPendingMO.getAddress() == null || mPendingMO.getAddress().length() == 0
  7. 372 || mPendingMO.getAddress().indexOf(PhoneNumberUtils.WILD) >= 0) {
  8. 373 // Phone number is invalid
  9. 374 mPendingMO.mCause = DisconnectCause.INVALID_NUMBER;
  10. 375
  11. 376 // handlePollCalls() will notice this call not present
  12. 377 // and will mark it as dropped.
  13. 378 pollCallsWhenSafe();
  14. 379 } else {
  15. 380 // Always unmute when initiating a new call
  16. 381 setMute(false);
  17. 382 //mCi的类型为CommandsInterface,在创建phone的时候作为参数,实际上执行的是RIL.dial()
  18. 383 mCi.dial(mPendingMO.getAddress(), mPendingMO.isEmergencyCall(),
  19. 384 mPendingMO.getEmergencyNumberInfo(), mPendingMO.hasKnownUserIntentEmergency(),
  20. 385 clirMode, uusInfo, obtainCompleteMessage());
  21. 386 }
  22. 387
  23. 388 if (mNumberConverted) {
  24. 389 mPendingMO.setConverted(origNumber);
  25. 390 mNumberConverted = false;
  26. 391 }
  27. 392
  28. 393 updatePhoneState();
  29. 394 mPhone.notifyPreciseCallStateChanged();
  30. 395
  31. 396 return mPendingMO;
  32. 397 }

 

其中mCi就是RIL的实例,mCi是CommandsInterface类型,在GsmCdmaPhone的构建中获取的

  1. public static void makeDefaultPhone(Context context) {
  2. synchronized (sLockProxyPhones) {
  3. ......
  4. sCommandsInterfaces[i] = new RIL(context, networkModes[i],
  5. cdmaSubscription, i);
  6. ......
  7. phone = new GsmCdmaPhone(context,
  8. sCommandsInterfaces[i], sPhoneNotifier, i,
  9. PhoneConstants.PHONE_TYPE_CDMA_LTE,
  10. TelephonyComponentFactory.getInstance());
  11. ......
  12. }
  1. @Override
  2. public void dial(String address, boolean isEmergencyCall, EmergencyNumber emergencyNumberInfo,
  3. boolean hasKnownUserIntentEmergency, int clirMode, UUSInfo uusInfo,
  4. Message result) {
  5. riljLog("dial" + "> " + "isEmergencyCall " + isEmergencyCall + " emergencyNumberInfo: " + emergencyNumberInfo
  6. + " mRadioVersion " + mRadioVersion);
  7. if (isEmergencyCall && mRadioVersion.greaterOrEqual(RADIO_HAL_VERSION_1_4)
  8. && emergencyNumberInfo != null) {
  9. emergencyDial(address, emergencyNumberInfo, hasKnownUserIntentEmergency, clirMode,
  10. uusInfo, result);
  11. return;
  12. }
  13. IRadio radioProxy = getRadioProxy(result);
  14. if (radioProxy != null) {
  15. RILRequest rr = obtainRequest(RIL_REQUEST_DIAL, result,
  16. mRILDefaultWorkSource);
  17. Dial dialInfo = new Dial();
  18. dialInfo.address = convertNullToEmptyString(address);
  19. dialInfo.clir = clirMode;
  20. if (uusInfo != null) {
  21. UusInfo info = new UusInfo();
  22. info.uusType = uusInfo.getType();
  23. info.uusDcs = uusInfo.getDcs();
  24. info.uusData = new String(uusInfo.getUserData());
  25. dialInfo.uusInfo.add(info);
  26. }
  27. if (RILJ_LOGD) {
  28. // Do not log function arg for privacy
  29. riljLog(rr.serialString() + "> " + requestToString(rr.mRequest));
  30. }
  31. try {
  32. radioProxy.dial(rr.mSerial, dialInfo);
  33. } catch (RemoteException | RuntimeException e) {
  34. handleRadioProxyExceptionForRR(rr, "dial", e);
  35. }
  36. }
  37. }

RIL与通话模块底层通讯过程

RIL通讯主要由RILSender和RILReceiver构成,用于通讯传输的载体的有 RILRequest,
Registrant(RegistrantList)。

  1. RILSender
    是一个Handler, 通过 #send(RILRequest) 将请求发送到 mSenderThread线程中,handleMessage 将请求写入mSocket中。
  2. RILReceiver
    在run内无限轮询,一旦读取到通话底层返回的数据,交给 #processResponse(Parcel)处理。
    其中应答分为有请求的应答,无请求的应答(即状态改变后的反馈)
    1.RIL_REQUEST_xxxx 有请求
    2.RIL_UNSOL_xxxx 无请求
  3. RILRequest
    成员变量:
    1.mSerial 请求序号,唯一,保证请求和反馈的一致。
    2.mRequest 请求类型 即 RIL_xxxx。
    3.mResult 用来发送请求的结果的句柄,由RIL请求的调用者提供。
  4. Registrant
           在 RIL内部维护着一系列的RegistrantList(Registrant的集合),每个集合代表一种状态改变的类型,对于有请求的应答,RIL是通过对应的mResult来发送结果的,但是对于无请求的应答,RIL是将反馈通知告诉对应的RegistrantList的(#notifyRegistrants),RegistrantList会通知每一个Registrant。在RIL的直接父类定义了这些RegistrantList,并提供了注册到RegistrantList的方法(eg.#registerForCallStateChanged,#unregisterForCallStateChanged)所以,如果想要监听通话状态的变化,那么就需要注册监听到对应的RegistrantList(监听着需要提供一个handler和一个int和object,handler用来发送数据,int区分监听的事件,object是额外的信息)。

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/988283
推荐阅读
相关标签
  

闽ICP备14008679号