本文主要是介绍Android Framework学习(四)之Launcher启动流程解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在之前的博客中,我们学习了init进程、Zygote进程和SyetemServer进程的启动过程,我们知道SystemServer进程主要用于启动系统的各种服务,二者其中就包含了负责启动Launcher的服务,LauncherAppService,本篇博客我们将一起学习Launcher相关的知识。
Launcher概述
Launcher程序就是我们平时看到的桌面程序,它其实也是一个Android应用程序,只不过这个应用程序是系统默认第一个启动的应用程序,Android系统启动的最后一步就是启动Launcher程序,应用程序Launcher在启动过程中会请求PackageManagerService返回系统中已经安装的应用程序的信息,并将这些信息封装成一个快捷图标列表显示在系统屏幕上,这样用户可以通过点击这些快捷图标来启动相应的应用程序。
Launcher启动流程
SystemServer进程的启动过程中会调用其main静态方法,开始执行整个SystemServer的启动流程,在其中通过调用三个内部方法分别启动boot service、core service和other service。在调用startOtherService方法中就会通过调用mActivityManagerService.systemReady()方法,而这个ActivityManagerService的systemReady函数就是启动Launcher的入口。
frameworks/base/services/Java/com/android/server/SystemServer.java
private void startOtherServices() {...mActivityManagerService.systemReady(new Runnable() {@Overridepublic void run() {Slog.i(TAG, "Making services ready");mSystemServiceManager.startBootPhase(SystemService.PHASE_ACTIVITY_MANAGER_READY);...
}
...
}
可以发现这个方法传递了一个Runnable参数,里面执行了各种其他服务的systemReady方法,这里不是我们关注的重点,我们看一下在ActivityManagerService中systemReady方法的具体实现
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public void systemReady(final Runnable goingCallback) {...// Start up initial activity.mBooting = true;startHomeActivityLocked(mCurrentUserId, "systemReady");...}
重点是在这个方法体中调用了startHomeActivityLocked方法,看其名字就是说开始执行启动homeActivity的操作
boolean startHomeActivityLocked(int userId, String reason) {if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL&& mTopAction == null) {//1return false;}Intent intent = getHomeIntent();//2ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);if (aInfo != null) {intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));aInfo = new ActivityInfo(aInfo);aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);ProcessRecord app = getProcessRecordLocked(aInfo.processName,aInfo.applicationInfo.uid, true);if (app == null || app.instrumentationClass == null) {//3intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);mActivityStarter.startHomeActivityLocked(intent, aInfo, reason);//4}} else {Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());}return true;}
注释1处的mFactoryTest代表系统的运行模式,系统的运行模式分为三种,分别是非工厂模式、低级工厂模式和高级工厂模式,mTopAction则用来描述第一个被启动Activity组件的Action,它的值为Intent.ACTION_MAIN。因此注释1的代码意思就是mFactoryTest为FactoryTest.FACTORY_TEST_LOW_LEVEL(低级工厂模式)并且mTopAction=null时,直接返回false,然后是调用getHomeIntent()方法
Intent getHomeIntent() {Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);intent.setComponent(mTopComponent);if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {intent.addCategory(Intent.CATEGORY_HOME);}return intent;}
getHomeIntent函数中创建了Intent,并将mTopAction和mTopData传入。mTopAction的值为Intent.ACTION_MAIN,并且如果系统运行模式不是低级工厂模式则将intent的Category设置为Intent.CATEGORY_HOME。Launcher的Intent对象中添加了Intent.CATEGORY_HOME常量,这个其实是一个launcher的标志,一般系统的启动页面Activity都会在androidmanifest.xml中配置这个标志。
我们再回到ActivityManagerService的startHomeActivityLocked函数,假设系统的运行模式不是低级工厂模式,在注释3处判断符合Action为Intent.ACTION_MAIN,Category为Intent.CATEGORY_HOME的应用程序是否已经启动,如果没启动则调用注释4的方法启动该应用程序。
startHomeActivityLocked方法中,经过一系列的判断逻辑之后最后调用了mStackSupervisor.startHomeActivity方法
void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason) {moveHomeStackTaskToTop(HOME_ACTIVITY_TYPE, reason);startActivityLocked(null /* caller */, intent, null /* resolvedType */, aInfo,null /* voiceSession */, null /* voiceInteractor */, null /* resultTo */,null /* resultWho */, 0 /* requestCode */, 0 /* callingPid */, 0 /* callingUid */,null /* callingPackage */, 0 /* realCallingPid */, 0 /* realCallingUid */,0 /* startFlags */, null /* options */, false /* ignoreTargetSecurity */,false /* componentSpecified */,null /* outActivity */, null /* container */, null /* inTask */);if (inResumeTopActivity) {// If we are in resume section already, home activity will be initialized, but not// resumed (to avoid recursive resume) and will stay that way until something pokes it// again. We need to schedule another resume.scheduleResumeTopActivities();}}
发现其调用的是scheduleResumeTopActivities()方法,这个方法中就是Activity的启动流程的逻辑了,此处不展开。
Launcher启动的Intent是一个隐士的Intent,所以我们会启动在androidmanifest.xml中配置了相同catogory的activity,android M中配置的这个catogory就是LauncherActivity。
LauncherActivity继承与ListActivity,我们看一下其Layout布局文件:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><ListView
android:id="@android:id/list"android:layout_width="match_parent"android:layout_height="match_parent"/><TextView
android:id="@android:id/empty"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:text="@string/activity_list_empty"android:visibility="gone"android:textAppearance="?android:attr/textAppearanceMedium"/></FrameLayout>
可以看到我们现实的桌面其实就是一个ListView控件,通过intent,应用程序Launcher就会被启动起来,并执行它的onCreate函数。
Launcher中应用图标显示流程
packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
@Overrideprotected void onCreate(Bundle savedInstanceState) {...LauncherAppState app = LauncherAppState.getInstance();//1mDeviceProfile = getResources().getConfiguration().orientation== Configuration.ORIENTATION_LANDSCAPE ?app.getInvariantDeviceProfile().landscapeProfile: app.getInvariantDeviceProfile().portraitProfile;mSharedPrefs = Utilities.getPrefs(this);mIsSafeModeEnabled = getPackageManager().isSafeMode();mModel = app.setLauncher(this);//2....if (!mRestoring) {if (DISABLE_SYNCHRONOUS_BINDING_CURRENT_PAGE) {mModel.startLoader(PagedView.INVALID_RESTORE_PAGE);//2} else {mModel.startLoader(mWorkspace.getRestorePage());}}
...}
注释1处获取LauncherAppState的实例并在注释2处调用它的setLauncher函数并将Launcher对象传入
packages/apps/Launcher3/src/com/android/launcher3/LauncherAppState.java
LauncherModel setLauncher(Launcher launcher) {getLauncherProvider().setLauncherProviderChangeListener(launcher);mModel.initialize(launcher);//1mAccessibilityDelegate = ((launcher != null) && Utilities.ATLEAST_LOLLIPOP) ?new LauncherAccessibilityDelegate(launcher) : null;return mModel;}
注释1处会调用LauncherModel的initialize函数:
public void initialize(Callbacks callbacks) {synchronized (mLock) {unbindItemInfosAndClearQueuedBindRunnables();mCallbacks = new WeakReference<Callbacks>(callbacks);}
}
在initialize函数中会将Callbacks,也就是传入的Launcher 封装成一个弱引用对象。因此我们得知mCallbacks变量指的就是封装成弱引用对象的Launcher,这个mCallbacks后文会用到它。
再回到Launcher的onCreate函数,在注释2处调用了LauncherModel的startLoader函数:
packages/apps/Launcher3/src/com/android/launcher3/LauncherModel.java
...@Thunk static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");//1static {sWorkerThread.start();}@Thunk static final Handler sWorker = new Handler(sWorkerThread.getLooper());//2
...public void startLoader(int synchronousBindPage, int loadFlags) {sInstallShortcutReceiver.enableInstallQueue();synchronized (mLock) {synchronized (mDeferredBindRunnables) {mDeferredBindRunnables.clear();}if (mCallbacks != null && mCallbacks.get() != null) {stopLoaderLocked();mLoaderTask = new LoaderTask(mApp.getContext(), loadFlags);//3if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE&& mAllAppsLoaded && mWorkspaceLoaded && !mIsLoaderTaskRunning) {mLoaderTask.runBindSynchronousPage(synchronousBindPage);} else {sWorkerThread.setPriority(Thread.NORM_PRIORITY);sWorker.post(mLoaderTask);//4}}}}
注释1处创建了具有消息循环的线程HandlerThread对象。注释2处创建了Handler,并且传入HandlerThread的Looper。Hander的作用就是向HandlerThread发送消息。在注释3处创建LoaderTask,在注释4处将LoaderTask作为消息发送给HandlerThread 。
LoaderTask类实现了Runnable接口,当LoaderTask所描述的消息被处理时则会调用它的run函数
private class LoaderTask implements Runnable {...public void run() {synchronized (mLock) {if (mStopped) {return;}mIsLoaderTaskRunning = true;}keep_running: {if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");loadAndBindWorkspace();//1if (mStopped) {break keep_running;}waitForIdle();if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");loadAndBindAllApps();//2}mContext = null;synchronized (mLock) {if (mLoaderTask == this) {mLoaderTask = null;}mIsLoaderTaskRunning = false;mHasLoaderCompletedOnce = true;}}... }
Launcher是用工作区的形式来显示系统安装的应用程序的快捷图标,每一个工作区都是来描述一个抽象桌面的,它由n个屏幕组成,每个屏幕又分n个单元格,每个单元格用来显示一个应用程序的快捷图标。注释1处调用loadAndBindWorkspace函数用来加载工作区信息,注释2处的loadAndBindAllApps函数是用来加载系统已经安装的应用程序信息
private void loadAndBindAllApps() {if (DEBUG_LOADERS) {Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);}if (!mAllAppsLoaded) {loadAllApps();//1synchronized (LoaderTask.this) {if (mStopped) {return;}}updateIconCache();synchronized (LoaderTask.this) {if (mStopped) {return;}mAllAppsLoaded = true;}} else {onlyBindAllApps();}
}
如果系统没有加载已经安装的应用程序信息,则会调用注释1处的loadAllApps函数:
private void loadAllApps() {
...mHandler.post(new Runnable() {public void run() {final long bindTime = SystemClock.uptimeMillis();final Callbacks callbacks = tryGetCallbacks(oldCallbacks);if (callbacks != null) {callbacks.bindAllApplications(added);//1if (DEBUG_LOADERS) {Log.d(TAG, "bound " + added.size() + " apps in "+ (SystemClock.uptimeMillis() - bindTime) + "ms");}} else {Log.i(TAG, "not binding apps: no Launcher activity");}}});...}
在注释1处会调用callbacks的bindAllApplications函数,在前面我们得知这个callbacks实际是指向Launcher的,因此我们来查看Launcher的bindAllApplications函数
packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
public void bindAllApplications(final ArrayList<AppInfo> apps) {if (waitUntilResume(mBindAllApplicationsRunnable, true)) {mTmpAppsList = apps;return;}if (mAppsView != null) {mAppsView.setApps(apps);//1}if (mLauncherCallbacks != null) {mLauncherCallbacks.bindAllApplications(apps);}
}
注释1处会调用AllAppsContainerView的setApps函数,并将包含应用信息的列表apps传进去
packages/apps/Launcher3/src/com/android/launcher3/allapps/AllAppsContainerView.java
public void setApps(List<AppInfo> apps) {mApps.setApps(apps);}
包含应用信息的列表apps已经设置到了AllAppsContainerView的AlphabeticalAppsList中,查看AllAppsContainerView的onFinishInflate函数:
@Overrideprotected void onFinishInflate() {super.onFinishInflate();
...// Load the all apps recycler viewmAppsRecyclerView = (AllAppsRecyclerView) findViewById(R.id.apps_list_view);//1mAppsRecyclerView.setApps(mApps);//2mAppsRecyclerView.setLayoutManager(mLayoutManager);mAppsRecyclerView.setAdapter(mAdapter);//3mAppsRecyclerView.setHasFixedSize(true);mAppsRecyclerView.addOnScrollListener(mElevationController);mAppsRecyclerView.setElevationController(mElevationController);
...}
onFinishInflate函数在加载完xml文件时就会调用,在注释1处得到AllAppsRecyclerView用来显示App列表,并在注释2处将apps的信息列表传进去,并在注释3处为AllAppsRecyclerView设置Adapter。这样应用程序快捷图标的列表就会显示在屏幕上。
总结
Launcher的启动流程
Zygote进程 –> SystemServer进程 –> startOtherService方法 –> ActivityManagerService的systemReady方法 –> startHomeActivityLocked方法 –> ActivityStackSupervisor的startHomeActivity方法 –> 执行Activity的启动逻辑,执行scheduleResumeTopActivities()方法
因为是隐试的启动Activity,所以启动的Activity就是在AndroidManifest.xml中配置catogery的值为:
public static final String CATEGORY_HOME = "android.intent.category.HOME";
这篇关于Android Framework学习(四)之Launcher启动流程解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!