从上一篇中,分析到,调用了PhoneApp的onCreate方法,从此进入了PhoneApp的世界,那么就需要看看其onCreate方法中究竟做了什么
public void onCreate() {从这儿,我们可以看到,其主要做了
if (UserHandle.myUserId() == 0) {
// We are running as the primary user, so should bring up the
// global phone state.
mPhoneGlobals = new PhoneGlobals(this);
mPhoneGlobals.onCreate();
mTelephonyGlobals = new TelephonyGlobals(this);
mTelephonyGlobals.onCreate();
}
}
1. 新建了PhoneGlobals对象,并且调用了其onCreate方法
2. 新建了TelephonyGlobals对象,并且调用了其onCreate方法
那么,这篇就来分析一下第一个类,PhoneGlobals
public void onCreate() {从这边的代码中,可以看到,在这个onCreate方法中,主要是做了
if (VDBG) Log.v(LOG_TAG, "onCreate()...");
ContentResolver resolver = getContentResolver();
// Cache the "voice capable" flag.
// This flag currently comes from a resource (which is
// overrideable on a per-product basis):
// Leo,固定值,默认为true,
// 从字面上的意思来看,应该是语音通话功能是否支持?
sVoiceCapable =
getResources().getBoolean(com.android.internal.R.bool.config_voice_capable);
// ...but this might eventually become a PackageManager "system
// feature" instead, in which case we'd do something like:
// sVoiceCapable =
// getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY_VOICE_CALLS);
// Leo,当第一次进来后,mCM为null
if (mCM == null) {
// Initialize the telephony framework
// Leo,调用PhoneFactory的makeDefaultPhones方法
// 此方法初始化Telephony的framework部分的代码,并且加载SIM卡的一些信息
// 同时和底层RIL进行连接通信
PhoneFactory.makeDefaultPhones(this);
// Start TelephonyDebugService After the default phone is created.
Intent intent = new Intent(this, TelephonyDebugService.class);
startService(intent);
// Leo,初始化CallManager对象
mCM = CallManager.getInstance();
// Leo,CallManager注册Phone
for (Phone phone : PhoneFactory.getPhones()) {
mCM.registerPhone(phone);
}
// Create the NotificationMgr singleton, which is used to display
// status bar icons and control other status bar behavior.
// Leo,初始化NotificationMgr对象,并且将当前对象传递给NotificationMgr
notificationMgr = NotificationMgr.init(this);
// If PhoneGlobals has crashed and is being restarted, then restart.
mHandler.sendEmptyMessage(EVENT_RESTART_SIP);
// Create an instance of CdmaPhoneCallState and initialize it to IDLE
// Leo,初始化CdmaPhoneCallState对象,并初始化其状态
cdmaPhoneCallState = new CdmaPhoneCallState();
cdmaPhoneCallState.CdmaPhoneCallStateInit();
// before registering for phone state changes
mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = mPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, LOG_TAG);
// lock used to keep the processor awake, when we don't care for the display.
mPartialWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE, LOG_TAG);
// Leo,初始化KeyguardManager对象
mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
// Get UpdateLock to suppress system-update related events (e.g. dialog show-up)
// during phone calls.
mUpdateLock = new UpdateLock("phone");
if (DBG) Log.d(LOG_TAG, "onCreate: mUpdateLock: " + mUpdateLock);
CallLogger callLogger = new CallLogger(this, new CallLogAsync());
// Leo,初始化CallGatewayManager对象
callGatewayManager = CallGatewayManager.getInstance();
// Create the CallController singleton, which is the interface
// to the telephony layer for user-initiated telephony functionality
// (like making outgoing calls.)
// Leo,初始化CallController对象
callController = CallController.init(this, callLogger, callGatewayManager);
// Create the CallerInfoCache singleton, which remembers custom ring tone and
// send-to-voicemail settings.
//
// The asynchronous caching will start just after this call.
callerInfoCache = CallerInfoCache.init(this);
// Leo,初始化PhoneInterfaceManager对象
phoneMgr = PhoneInterfaceManager.init(this, PhoneFactory.getDefaultPhone());
// Leo,初始化CarrierConfigLoader对象
configLoader = CarrierConfigLoader.init(this);
// Create the CallNotifer singleton, which handles
// asynchronous events from the telephony layer (like
// launching the incoming-call UI when an incoming call comes
// in.)
// Leo,初始化CallNotifier对象
notifier = CallNotifier.init(this);
PhoneUtils.registerIccStatus(mHandler, EVENT_SIM_NETWORK_LOCKED);
// register for MMI/USSD
mCM.registerForMmiComplete(mHandler, MMI_COMPLETE, null);
// register connection tracking to PhoneUtils
PhoneUtils.initializeConnectionHandler(mCM);
// Register for misc other intent broadcasts.
IntentFilter intentFilter =
new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
registerReceiver(mReceiver, intentFilter);
//set the default values for the preferences in the phone.
PreferenceManager.setDefaultValues(this, R.xml.network_setting, false);
PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false);
// Make sure the audio mode (along with some
// audio-mode-related state of our own) is initialized
// correctly, given the current state of the phone.
PhoneUtils.setAudioMode(mCM);
}
cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData();
cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData();
cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState();
cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState();
simActivationManager = new SimActivationManager();
// XXX pre-load the SimProvider so that it's ready
resolver.getType(Uri.parse("content://icc/adn"));
// TODO: Register for Cdma Information Records
// phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null);
// Read HAC settings and configure audio hardware
if (getResources().getBoolean(R.bool.hac_enabled)) {
int hac = android.provider.Settings.System.getInt(
getContentResolver(),
android.provider.Settings.System.HEARING_AID,
0);
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setParameter(SettingsConstants.HAC_KEY,
hac == SettingsConstants.HAC_ENABLED
? SettingsConstants.HAC_VAL_ON : SettingsConstants.HAC_VAL_OFF);
}
}
1. 调用了PhoneFactory的makeDefaultPhones方法
2. 初始化了一些类,这个初始化的操作相对较为简单,此地不再分析
PhoneFactory的makeDefaultPhones方法,在此前分析的SIM卡开机流程中有提到,此方法是在开机后,加载SIM卡数据和做一些Phone相关的初始化操作,这个方法也是本篇中将要分析的重点。
public static void makeDefaultPhones(Context context) {
makeDefaultPhone(context);
}
public static void makeDefaultPhone(Context context) { synchronized (sLockProxyPhones) { if (!sMadeDefaults) { sContext = context; // create the telephony device controller. TelephonyDevController.create(); int retryCount = 0; for(;;) { boolean hasException = false; retryCount ++; try { // use UNIX domain socket to // prevent subsequent initialization new LocalServerSocket("com.android.internal.telephony"); } catch (java.io.IOException ex) { hasException = true; } if ( !hasException ) { break; } else if (retryCount > SOCKET_OPEN_MAX_RETRY) { throw new RuntimeException("PhoneFactory probably already running"); } else { try { Thread.sleep(SOCKET_OPEN_RETRY_MILLIS); } catch (InterruptedException er) { } } } sPhoneNotifier = new DefaultPhoneNotifier(); int cdmaSubscription = CdmaSubscriptionSourceManager.getDefault(context); Rlog.i(LOG_TAG, "Cdma Subscription set to " + cdmaSubscription); /* In case of multi SIM mode two instances of Phone, RIL are created, where as in single SIM mode only instance. isMultiSimEnabled() function checks whether it is single SIM or multi SIM mode */ // Leo, 获取设备支持的最大SIM卡数 int numPhones = TelephonyManager.getDefault().getPhoneCount(); int[] networkModes = new int[numPhones]; sPhones = new Phone[numPhones]; sCommandsInterfaces = new RIL[numPhones]; sTelephonyNetworkFactories = new TelephonyNetworkFactory[numPhones]; for (int i = 0; i < numPhones; i++) { // reads the system properties and makes commandsinterface // Get preferred network type. networkModes[i] = RILConstants.PREFERRED_NETWORK_MODE; Rlog.i(LOG_TAG, "Network Mode set to " + Integer.toString(networkModes[i])); sCommandsInterfaces[i] = new RIL(context, networkModes[i], cdmaSubscription, i); } Rlog.i(LOG_TAG, "Creating SubscriptionController"); SubscriptionController.init(context, sCommandsInterfaces); // Instantiate UiccController so that all other classes can just // call getInstance() sUiccController = UiccController.make(context, sCommandsInterfaces); for (int i = 0; i < numPhones; i++) { Phone phone = null; int phoneType = TelephonyManager.getPhoneType(networkModes[i]); if (phoneType == PhoneConstants.PHONE_TYPE_GSM) { phone = new GsmCdmaPhone(context, sCommandsInterfaces[i], sPhoneNotifier, i, PhoneConstants.PHONE_TYPE_GSM, TelephonyComponentFactory.getInstance()); } else if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) { phone = new GsmCdmaPhone(context, sCommandsInterfaces[i], sPhoneNotifier, i, PhoneConstants.PHONE_TYPE_CDMA_LTE, TelephonyComponentFactory.getInstance()); } Rlog.i(LOG_TAG, "Creating Phone with type = " + phoneType + " sub = " + i); sPhones[i] = phone; } // Set the default phone in base class. // FIXME: This is a first best guess at what the defaults will be. It // FIXME: needs to be done in a more controlled manner in the future. sPhone = sPhones[0]; sCommandsInterface = sCommandsInterfaces[0]; // Ensure that we have a default SMS app. Requesting the app with // updateIfNeeded set to true is enough to configure a default SMS app. ComponentName componentName = SmsApplication.getDefaultSmsApplication(context, true /* updateIfNeeded */); String packageName = "NONE"; if (componentName != null) { packageName = componentName.getPackageName(); } Rlog.i(LOG_TAG, "defaultSmsApplication: " + packageName); // Set up monitor to watch for changes to SMS packages SmsApplication.initSmsPackageMonitor(context); sMadeDefaults = true; Rlog.i(LOG_TAG, "Creating SubInfoRecordUpdater "); // Leo,新建一个SubscriptionInfoUpdater对象 sSubInfoRecordUpdater = new SubscriptionInfoUpdater(context, sPhones, sCommandsInterfaces); SubscriptionController.getInstance().updatePhonesAvailability(sPhones); // Start monitoring after defaults have been made. // Default phone must be ready before ImsPhone is created // because ImsService might need it when it is being opened. for (int i = 0; i < numPhones; i++) { sPhones[i].startMonitoringImsService(); } ITelephonyRegistry tr = ITelephonyRegistry.Stub.asInterface( ServiceManager.getService("telephony.registry")); SubscriptionController sc = SubscriptionController.getInstance(); sSubscriptionMonitor = new SubscriptionMonitor(tr, sContext, sc, numPhones); sPhoneSwitcher = new PhoneSwitcher(MAX_ACTIVE_PHONES, numPhones, sContext, sc, Looper.myLooper(), tr, sCommandsInterfaces, sPhones); sProxyController = ProxyController.getInstance(context, sPhones, sUiccController, sCommandsInterfaces, sPhoneSwitcher); sTelephonyNetworkFactories = new TelephonyNetworkFactory[numPhones]; for (int i = 0; i < numPhones; i++) { sTelephonyNetworkFactories[i] = new TelephonyNetworkFactory( sPhoneSwitcher, sc, sSubscriptionMonitor, Looper.myLooper(), sContext, i, sPhones[i].mDcTracker); } } }}此前,在SIM卡开机流程中,已经分析过前面的几个类的初始化和所做的一些操作,此处由于是分析Telephony相关,因此,本篇,只分析后面两个类的初始化(PhoneSwitcher和TelephonyNetworkFactory)
1. PhoneSwitcher类
sPhoneSwitcher = new PhoneSwitcher(MAX_ACTIVE_PHONES, numPhones,根据上面的分析,此方法所传入的参数有:第一个参数为设备支持的最大可激活的phone数量,此处为默认值1,第二个参数为设备支持的Phone数量(即卡槽数),此处为2,第三个参数为上下文对象,第四个参数为上文初始化的SubscriptionController对象,第五个参数为主线程的Looper,第六个参数为TelephonyRegitry对象,第七个参数为RIL对象,和Phone对应,第八个参数为卡槽支持的所有Phone数组
sContext, sc, Looper.myLooper(), tr, sCommandsInterfaces,
sPhones);
PhoneSwitcher的构造方法
/*此处,新建了一个PhoneSwitcherNetworkRequestListener对象,并调用了其register方法,那么PhoneSwitcherNetworkRequestListener是什么?
* Leo
* maxActivePhones: 最大允许激活的Phone数量,此处为1
* numPhones:最大支持的SIM卡数量,这边是2
* context:上下文对象
* subscriptionController:SubscriptionController.getInstance得到的SubscriptionController对象
* looper: Looper.myLooper()
* tr:TelephonyRegistry对象
* cis:RIL对象数组,对应每张卡
* phones:每个卡槽对应的Phone数组
*/
public PhoneSwitcher(int maxActivePhones, int numPhones, Context context,
SubscriptionController subscriptionController, Looper looper, ITelephonyRegistry tr,
CommandsInterface[] cis, Phone[] phones) {
super(looper);
mContext = context;
mNumPhones = numPhones;
mPhones = phones;
mPhoneSubscriptions = new int[numPhones];
mMaxActivePhones = maxActivePhones;
mLocalLog = new LocalLog(MAX_LOCAL_LOG_LINES);
mSubscriptionController = subscriptionController;
mActivePhoneRegistrants = new RegistrantList[numPhones];
mPhoneStates = new PhoneState[numPhones];
for (int i = 0; i < numPhones; i++) {
mActivePhoneRegistrants[i] = new RegistrantList();
mPhoneStates[i] = new PhoneState();
if (mPhones[i] != null) {
mPhones[i].registerForEmergencyCallToggle(this, EVENT_EMERGENCY_TOGGLE, null);
}
}
mCommandsInterfaces = cis;
try {
tr.addOnSubscriptionsChangedListener("PhoneSwitcher", mSubscriptionsChangedListener);
} catch (RemoteException e) {
}
mContext.registerReceiver(mDefaultDataChangedReceiver,
new IntentFilter(TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED));
NetworkCapabilities netCap = new NetworkCapabilities();
netCap.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS);
netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_SUPL);
netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_DUN);
netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_FOTA);
netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_IMS);
netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_CBS);
netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_IA);
netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_RCS);
netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_XCAP);
netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_EIMS);
netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
netCap.setNetworkSpecifier(NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER);
// Leo,初始化PhoneSwitcherNetworkRequestListener对象
NetworkFactory networkFactory = new PhoneSwitcherNetworkRequestListener(looper, context,
netCap, this);
// we want to see all requests
networkFactory.setScoreFilter(101);
// Leo,调用了PhoneSwicherNetworkRequestListener的register方法
networkFactory.register();
log("PhoneSwitcher started");
}
private static class PhoneSwitcherNetworkRequestListener extends NetworkFactory {可以看到,PhoneSwitcherNetworkRequestListener类,仅仅是重写了其父类NetworkFactory的needNetworkFor和releaseNetworkFor方法,因此,其调用的register方法,其实是调用的其父类NetworkFactory的register方法
private final PhoneSwitcher mPhoneSwitcher;
public PhoneSwitcherNetworkRequestListener (Looper l, Context c,
NetworkCapabilities nc, PhoneSwitcher ps) {
super(l, c, "PhoneSwitcherNetworkRequstListener", nc);
mPhoneSwitcher = ps;
}
@Override
protected void needNetworkFor(NetworkRequest networkRequest, int score) {
if (VDBG) log("needNetworkFor " + networkRequest + ", " + score);
Message msg = mPhoneSwitcher.obtainMessage(EVENT_REQUEST_NETWORK);
msg.obj = networkRequest;
msg.sendToTarget();
}
@Override
protected void releaseNetworkFor(NetworkRequest networkRequest) {
if (VDBG) log("releaseNetworkFor " + networkRequest);
Message msg = mPhoneSwitcher.obtainMessage(EVENT_RELEASE_NETWORK);
msg.obj = networkRequest;
msg.sendToTarget();
}
}
那么,我们先来看下NetworkFactory的构造方法,然后在分析其register方法
public NetworkFactory(Looper looper, Context context, String logTag,这个构造方法中,只是初始化了一些值,注意此处的LOG_TAG被设置为PhoneSwitcherNetworkRequestListener字串
NetworkCapabilities filter) {
super(looper);
LOG_TAG = logTag;
mContext = context;
mCapabilityFilter = filter;
}
public void register() {初始化一个Messenger对象,并且作为参数传入registryNetworkFactory方法中,那么ConnectivityManager.from(mContext)是什么?
if (DBG) log("Registering NetworkFactory");
if (mMessenger == null) {
mMessenger = new Messenger(this);
ConnectivityManager.from(mContext).registerNetworkFactory(mMessenger, LOG_TAG);
}
}
public static ConnectivityManager from(Context context) {根据此前对getSystemService方法的分析,我们知道,其应该是在SystemServiceRegister类中定义的
return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
registerService(Context.CONNECTIVITY_SERVICE, ConnectivityManager.class,果然,此处定义了ConnectivityManager对象,而ServiceManager.getService(Context.CONNECTIVITY_SERVICE)是在SystemServer中定义的
new StaticApplicationContextServiceFetcher<ConnectivityManager>() {
@Override
public ConnectivityManager createService(Context context) {
IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
// Leo, 新建一个ConnectivityManager对象,并且其构造方法中的第二个参数为ConnectivityService对象
return new ConnectivityManager(context, service);
}});
try {因此,我们得出结论,ConnectivityManager.from(mContext),事实上就是初始化ConnectivityManager的过程,而且其的mService参数被设定为ConnectivityService对象
connectivity = new ConnectivityService(
context, networkManagement, networkStats, networkPolicy);
ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
networkStats.bindConnectivityManager(connectivity);
networkPolicy.bindConnectivityManager(connectivity);
} catch (Throwable e) {
reportWtf("starting Connectivity Service", e);
}
回到此前,NetworkFactory类中的register方法,就是调用了ConnectivityManager对象的registryNetworkFactory方法,并且其参数分别为Messager对象和PhoneSwitcherNetworkRequestListener字串
public void registerNetworkFactory(Messenger messenger, String name) {调用的是ConnectivityService对象的registerNetworkFactory方法
try {
mService.registerNetworkFactory(messenger, name);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
public void registerNetworkFactory(Messenger messenger, String name) {此处新建一个NetworkFactoryInfo对象并且将刚刚的两个参数,和新建的AsyncChannel对象,添加进去,之后发送EVENT_REGISTER_NETWORK_FACTORY消息
enforceConnectivityInternalPermission();
NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
}
case EVENT_REGISTER_NETWORK_FACTORY: {
handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
break;
}
private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) { if (DBG) log("Got NetworkFactory Messenger for " + nfi.name); mNetworkFactoryInfos.put(nfi.messenger, nfi); nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);}调用AsyncChannel对象的connect方法,注意传入的参数,第一个参数为上下文对象,第二个参数为ConnectivityService中的mTrackerHandler对象,第三个参数为NetworkFactory中新建的Messager对象
public void connect(Context srcContext, Handler srcHandler, Messenger dstMessenger) {因此,先调用了connected方法,后调用replyHalfConnected方法
if (DBG) log("connect srcHandler to the dstMessenger E");
// We are connected
connected(srcContext, srcHandler, dstMessenger);
// Tell source we are half connected
replyHalfConnected(STATUS_SUCCESSFUL);
if (DBG) log("connect srcHandler to the dstMessenger X");
}
public void connected(Context srcContext, Handler srcHandler, Messenger dstMessenger) {connected方法较为简单,只是初始化了一些参数,注意其中的参数指向
if (DBG) log("connected srcHandler to the dstMessenger E");
// Initialize source fields
mSrcContext = srcContext;
mSrcHandler = srcHandler;
mSrcMessenger = new Messenger(mSrcHandler);
// Initialize destination fields
mDstMessenger = dstMessenger;
linkToDeathMonitor();
if (DBG) log("connected srcHandler to the dstMessenger X");
}
private void replyHalfConnected(int status) {此处,通过mSrcHandler发送了CMD_CHANNEL_HALF_CONNECTED,那么mSrcHandler是什么,参照前面的connected方法,mSrcHandler就是ConnectivityService中的mTrackHandler,因此是在ConnectivityService中进行处理,其中消息的arg1参数为STATUS_SUCCESSFUL,replyTo参数为mDstMessager,参照connected方法,为NetworkFactory中的Messager对象
Message msg = mSrcHandler.obtainMessage(CMD_CHANNEL_HALF_CONNECTED);
msg.arg1 = status;
msg.obj = this;
msg.replyTo = mDstMessenger;
if (!linkToDeathMonitor()) {
// Override status to indicate failure
msg.arg1 = STATUS_BINDING_UNSUCCESSFUL;
}
mSrcHandler.sendMessage(msg);
}
因此,进入ConnectivityService中处理消息
case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
handleAsyncChannelHalfConnect(msg);
break;
}
private void handleAsyncChannelHalfConnect(Message msg) { AsyncChannel ac = (AsyncChannel) msg.obj; if (mNetworkFactoryInfos.containsKey(msg.replyTo)) { if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { if (VDBG) log("NetworkFactory connected"); // A network factory has connected. Send it all current NetworkRequests. for (NetworkRequestInfo nri : mNetworkRequests.values()) { if (nri.request.isListen()) continue; NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId); ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, (nai != null ? nai.getCurrentScore() : 0), 0, nri.request); } } else { loge("Error connecting NetworkFactory"); mNetworkFactoryInfos.remove(msg.obj); } } ......}满足上面这个if语句的条件,为什么?请参照前面的代码
AsyncChannel对象调用sendMessage发出CMD_REQUEST_NETWORK消息
public void sendMessage(int what, int arg1, int arg2, Object obj) {
Message msg = Message.obtain();
msg.what = what;
msg.arg1 = arg1;
msg.arg2 = arg2;
msg.obj = obj;
sendMessage(msg);
}
public void sendMessage(Message msg) { msg.replyTo = mSrcMessenger; try { mDstMessenger.send(msg); } catch (RemoteException e) { replyDisconnected(STATUS_SEND_UNSUCCESSFUL); }}因此,使用了NetworkFactory中的Messager来发送消息,并在NetworkFactory中进行处理
case CMD_REQUEST_NETWORK: {obj为NetworkRequest对象,而arg1为score
handleAddRequest((NetworkRequest)msg.obj, msg.arg1);
break;
}
protected void handleAddRequest(NetworkRequest request, int score) {
// Leo,第一次进入,无次requestid
NetworkRequestInfo n = mNetworkRequests.get(request.requestId);
if (n == null) {
if (DBG) log("got request " + request + " with score " + score);
// Leo,初始化
n = new NetworkRequestInfo(request, score);
// Leo,add
mNetworkRequests.put(n.request.requestId, n);
} else {
if (VDBG) log("new score " + score + " for exisiting request " + request);
n.score = score;
}
if (VDBG) log(" my score=" + mScore + ", my filter=" + mCapabilityFilter);
// Leo,调用evalRequest方法
evalRequest(n);
}
private void evalRequest(NetworkRequestInfo n) { if (VDBG) log("evalRequest"); if (n.requested == false && n.score < mScore && n.request.networkCapabilities.satisfiedByNetworkCapabilities( mCapabilityFilter) && acceptRequest(n.request, n.score)) { if (VDBG) log(" needNetworkFor"); needNetworkFor(n.request, n.score); n.requested = true; } else if (n.requested == true && (n.score > mScore || n.request.networkCapabilities.satisfiedByNetworkCapabilities( mCapabilityFilter) == false || acceptRequest(n.request, n.score) == false)) { if (VDBG) log(" releaseNetworkFor"); releaseNetworkFor(n.request); n.requested = false; } else { if (VDBG) log(" done"); }}因此,最终调用的是needNetworkFor方法
综上,我们看到,调用NetworkFactory的register方法,最终会生成一个NetworkRequestInfo类,并且会直接调用needNetworkFor方法
而PhoneSwitcherNetworkRequestListener类中,重写了其父类的needNetworkFor方法,因此
protected void needNetworkFor(NetworkRequest networkRequest, int score) {
if (VDBG) log("needNetworkFor " + networkRequest + ", " + score);
Message msg = mPhoneSwitcher.obtainMessage(EVENT_REQUEST_NETWORK);
msg.obj = networkRequest;
msg.sendToTarget();
}
case EVENT_REQUEST_NETWORK: { onRequestNetwork((NetworkRequest)msg.obj); break;}
private void onRequestNetwork(NetworkRequest networkRequest) { final DcRequest dcRequest = new DcRequest(networkRequest, mContext); if (mPrioritizedDcRequests.contains(dcRequest) == false) { mPrioritizedDcRequests.add(dcRequest); Collections.sort(mPrioritizedDcRequests); onEvaluate(REQUESTS_CHANGED, "netRequest"); }}添加dcRequest到mPrioritizedDcRequests中,并且调用onEvaluate方法
private void onEvaluate(boolean requestsChanged, String reason) {激活Phone,由于此前设定的mMaxActivePhones值为1,因此只能有一个phone处于激活状态
StringBuilder sb = new StringBuilder(reason);
if (isEmergency()) {
log("onEvalute aborted due to Emergency");
return;
}
boolean diffDetected = requestsChanged;
final int dataSub = mSubscriptionController.getDefaultDataSubId();
if (dataSub != mDefaultDataSubscription) {
sb.append(" default ").append(mDefaultDataSubscription).append("->").append(dataSub);
mDefaultDataSubscription = dataSub;
diffDetected = true;
}
for (int i = 0; i < mNumPhones; i++) {
int sub = mSubscriptionController.getSubIdUsingPhoneId(i);
if (sub != mPhoneSubscriptions[i]) {
sb.append(" phone[").append(i).append("] ").append(mPhoneSubscriptions[i]);
sb.append("->").append(sub);
mPhoneSubscriptions[i] = sub;
diffDetected = true;
}
}
if (diffDetected) {
log("evaluating due to " + sb.toString());
List<Integer> newActivePhones = new ArrayList<Integer>();
for (DcRequest dcRequest : mPrioritizedDcRequests) {
int phoneIdForRequest = phoneIdForRequest(dcRequest.networkRequest);
if (phoneIdForRequest == INVALID_PHONE_INDEX) continue;
if (newActivePhones.contains(phoneIdForRequest)) continue;
newActivePhones.add(phoneIdForRequest);
if (newActivePhones.size() >= mMaxActivePhones) break;
}
......
for (int phoneId = 0; phoneId < mNumPhones; phoneId++) {
if (newActivePhones.contains(phoneId) == false) {
deactivate(phoneId);
}
}
// only activate phones up to the limit
for (int phoneId : newActivePhones) {
activate(phoneId);
}
}
}
private void activate(int phoneId) { PhoneState state = mPhoneStates[phoneId]; if (state.active == true) return; state.active = true; log("activate " + phoneId); state.lastRequested = System.currentTimeMillis(); mCommandsInterfaces[phoneId].setDataAllowed(true, null); mActivePhoneRegistrants[phoneId].notifyRegistrants();}修改Phone的状态为数据激活状态,并且允许其数据连接,并发送给modem层,允许该卡数据连接
那么PhoneSwitcher的初始化就分析结束了,接下来,我们分析另一个类,TelephonyNetworkFactory
2. TelephonyNetworkFactory
sTelephonyNetworkFactories[i] = new TelephonyNetworkFactory(该类的初始化的参数主要有,第一个参数为刚刚初始化的PhoneSwitcher对象,第二个参数为SubscriptionController对象,第三个参数为SubscriptionMonitor对象,第四个参数为PhoneGlobals线程的Looper,第五个参数为上下文对象,第六个参数为卡槽index,第七个参数为phone对应的DcTracker对象
sPhoneSwitcher, sc, sSubscriptionMonitor, Looper.myLooper(),
sContext, i, sPhones[i].mDcTracker);
public TelephonyNetworkFactory(PhoneSwitcher phoneSwitcher,
SubscriptionController subscriptionController, SubscriptionMonitor subscriptionMonitor,
Looper looper, Context context, int phoneId, DcTracker dcTracker) {
super(looper, context, "TelephonyNetworkFactory[" + phoneId + "]", null);
mInternalHandler = new InternalHandler(looper);
setCapabilityFilter(makeNetworkFilter(subscriptionController, phoneId));
setScoreFilter(TELEPHONY_NETWORK_SCORE);
mPhoneSwitcher = phoneSwitcher;
mSubscriptionController = subscriptionController;
mSubscriptionMonitor = subscriptionMonitor;
mPhoneId = phoneId;
LOG_TAG = "TelephonyNetworkFactory[" + phoneId + "]";
mDcTracker = dcTracker;
mIsActive = false;
// Leo,注册ActivePhoneSwitcher消息
mPhoneSwitcher.registerForActivePhoneSwitch(mPhoneId, mInternalHandler,
EVENT_ACTIVE_PHONE_SWITCH, null);
mSubscriptionId = INVALID_SUBSCRIPTION_ID;
mSubscriptionMonitor.registerForSubscriptionChanged(mPhoneId, mInternalHandler,
EVENT_SUBSCRIPTION_CHANGED, null);
mIsDefault = false;
mSubscriptionMonitor.registerForDefaultDataSubscriptionChanged(mPhoneId, mInternalHandler,
EVENT_DEFAULT_SUBSCRIPTION_CHANGED, null);
register();
}
此构造方法主要是做了
1. 初始化一些参数
2. 调用PhoneSwitcher的registerForActivePhoneSwitcher方法
3. 调用SubscriptionMonitor的registerForSUbscriptionChanged方法
4. 调用SubscriptionMonitor的registerForDefaultDataSubscriptionChanged方法
5. 调用其父类NetworkRequest的register方法
那么接下来,初始化参数部分比较简单,自己看下就好,先看第二个任务,调用PhoneSwitcher的registerForActivePhoneSwitcher方法
public void registerForActivePhoneSwitch(int phoneId, Handler h, int what, Object o) {通过传入的参数,新建Registrant对象,并添加到mActivePhoneRegistrants中,然后发送消息
validatePhoneId(phoneId);
Registrant r = new Registrant(h, what, o);
mActivePhoneRegistrants[phoneId].add(r);
r.notifyRegistrant();
}
public void
notifyRegistrant()
{
internalNotifyRegistrant (null, null);
}
/*package*/ void internalNotifyRegistrant (Object result, Throwable exception) { Handler h = getHandler(); if (h == null) { clear(); } else { Message msg = Message.obtain(); msg.what = what; msg.obj = new AsyncResult(userObj, result, exception); h.sendMessage(msg); } }可以看到,此方法就是通过传入的handler对象,发送EVENT_ACTIVE_PHONE_SWITCH的消息,而handler为TelephonyNetworkFactory类中传入的mInternalHandler对象,因此在TelephonyNetworkFactory中进行处理消息
case EVENT_ACTIVE_PHONE_SWITCH: {
onActivePhoneSwitch();
break;
}
private void onActivePhoneSwitch() { final boolean newIsActive = mPhoneSwitcher.isPhoneActive(mPhoneId); if (mIsActive != newIsActive) { mIsActive = newIsActive; String logString = "onActivePhoneSwitch(" + mIsActive + ", " + mIsDefault + ")"; if (DBG) log(logString); if (mIsDefault) { applyRequests(mDefaultRequests, (mIsActive ? REQUEST : RELEASE), logString); } applyRequests(mSpecificRequests, (mIsActive ? REQUEST : RELEASE), logString); }}刚刚在分析PhoneSwitcher的时候,我们知道,在最后,是激活了默认Phone,并且将其active状态置为true,因此,此处直接将mIsActive置为true
由于mSpecificRequests size为0,因此applyRequests就不会走了
接下来在TelephonyNetworkFactory的构造方法中调用的是SubscriptionMonitor的registerForDefaultDataSubscriptionChanged方法
public void registerForDefaultDataSubscriptionChanged(int phoneId, Handler h, int what,和之前一样,使用TelephonyNetworkFactory的mInternalHandler发送EVENT_DEFAULT_SUBSCRIPTION_CHANGED消息
Object o) {
if (invalidPhoneId(phoneId)) {
throw new IllegalArgumentException("Invalid PhoneId");
}
Registrant r = new Registrant(h, what, o);
mDefaultDataSubChangedRegistrants[phoneId].add(r);
r.notifyRegistrant();
}
case EVENT_DEFAULT_SUBSCRIPTION_CHANGED: {
onDefaultChange();
break;
}
private void onDefaultChange() { final int newDefaultSubscriptionId = mSubscriptionController.getDefaultDataSubId(); final boolean newIsDefault = (newDefaultSubscriptionId == mSubscriptionId); if (newIsDefault != mIsDefault) { mIsDefault = newIsDefault; String logString = "onDefaultChange(" + mIsActive + "," + mIsDefault + ")"; if (DBG) log(logString); if (mIsActive == false) return; applyRequests(mDefaultRequests, (mIsDefault ? REQUEST : RELEASE), logString); }}可以看到,和此前一致,设定mIsDefault为true
那么接下来,在构造方法中就需要调用TelephonyNetworkFactory的父类NetworkFactory的register方法,通过前面对于register的方法分析,我们知道,其最终会调用TelephonyNetworkFactory的needNetworkFor方法
public void needNetworkFor(NetworkRequest networkRequest, int score) {
Message msg = mInternalHandler.obtainMessage(EVENT_NETWORK_REQUEST);
msg.obj = networkRequest;
msg.sendToTarget();
}
case EVENT_NETWORK_REQUEST: { onNeedNetworkFor(msg); break;}
private void onNeedNetworkFor(Message msg) { NetworkRequest networkRequest = (NetworkRequest)msg.obj; boolean isApplicable = false; LocalLog localLog = null; if (TextUtils.isEmpty(networkRequest.networkCapabilities.getNetworkSpecifier())) { // request only for the default network localLog = mDefaultRequests.get(networkRequest); if (localLog == null) { localLog = new LocalLog(REQUEST_LOG_SIZE); localLog.log("created for " + networkRequest); mDefaultRequests.put(networkRequest, localLog); isApplicable = mIsDefault; } } else { localLog = mSpecificRequests.get(networkRequest); if (localLog == null) { localLog = new LocalLog(REQUEST_LOG_SIZE); mSpecificRequests.put(networkRequest, localLog); isApplicable = true; } } if (mIsActive && isApplicable) { String s = "onNeedNetworkFor"; localLog.log(s); log(s + " " + networkRequest); mDcTracker.requestNetwork(networkRequest, localLog); } else { String s = "not acting - isApp=" + isApplicable + ", isAct=" + mIsActive; localLog.log(s); log(s + " " + networkRequest); }}此前,我们分析过,mIsActive和mIsDefault均已经被置为true,因此,会调用mDcTracker的requestNetwork方法
由此,我们进入了DcTracker的数据连接模块