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

Android 6.0 Launcher2 應用啟動源碼解析

編輯:關於 Android 程式設計

此前我們分析了 Android 6.0 系統在啟動時安裝應用的過程,這些應用安裝完成後,Launcher 應用便負責把它們在桌面上呈現出來。

一、AMS 啟動 Launcher

Launcher 是在 AMS 的 systemReady 方法中直接呼叫 startHomeActivityLocked 啟動的,下面是 systemReady 啟動 Launcher 的程式碼。

startHomeActivityLocked(mCurrentUserId, "systemReady");

來看這個函式,它先呼叫 getHomeIntent 取得 Intent,再呼叫 resolveActivityInfo 從 PKMS 取得 ActivityInfo,接著當行程尚未啟動時,呼叫 ActivityStackSupervisor 的 startHomeActivity 函式。

 boolean startHomeActivityLocked(int userId, String reason) { if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL && mTopAction == null) { return false; } Intent intent = getHomeIntent(); ActivityInfo 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) { intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); mStackSupervisor.startHomeActivity(intent, aInfo, reason); } } return true; }

先看 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; }

再看 ActivityStackSupervisor 的 startHomeActivity,它也是呼叫 startActivityLocked 來啟動 Activity,這個函式在之前的部落格分析過,這裡不再贅述。

 void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason) { moveHomeStackTaskToTop(HOME_ACTIVITY_TYPE, reason); startActivityLocked(null, intent, null, aInfo, null, null, null, null, 0, 0, 0, null, 0, 0, 0, null, false, false, null, null, null); if (inResumeTopActivity) { scheduleResumeTopActivities(); } }

二、Launcher 啟動

接著看 Launcher 的 AndroidManifest.xml,其主 Activity 有一個 category 為 android.intent.category.HOME:

 <application android:name="com.android.launcher2.LauncherApplication" android:label="@string/application_name" android:icon="@mipmap/ic_launcher_home" android:hardwareAccelerated="true" android:largeHeap="@bool/config_largeHeap" android:supportsRtl="true"> <activity android:name="com.android.launcher2.Launcher" android:launchMode="singleTask" android:clearTaskOnLaunch="true" android:stateNotNeeded="true" android:resumeWhilePausing="true" android:theme="@style/Theme" android:windowSoftInputMode="adjustPan" android:screenOrientation="nosensor"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.HOME" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.MONKEY"/> </intent-filter> </activity>

在 Launcher.java 的 onCreate 函式中呼叫了 mModel.startLoader:

 protected void onCreate(Bundle savedInstanceState) { ...... if (!mRestoring) { if (sPausedFromUserAction) { mModel.startLoader(true, -1); } else { mModel.startLoader(true, mWorkspace.getCurrentPage()); } } ......

startLoader 函式會 post 一個 Runnable 訊息,來看它的 run 方法:

 public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { mDeferredBindRunnables.clear(); if (mCallbacks != null && mCallbacks.get() != null) { isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp, isLaunching); if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } }

在其 run 方法中會呼叫 loadAndBindAllApps,而後者又會呼叫 loadAllAppsByBatch:

 public void run() { synchronized (mLock) { mIsLoaderTaskRunning = true; } final Callbacks cbk = mCallbacks.get(); final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true; keep_running: { synchronized (mLock) { Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (loadWorkspaceFirst) { loadAndBindWorkspace(); } else { loadAndBindAllApps(); }

先看 loadAllAppsByBatch 函式,它進入 while 迴圈後呼叫 LauncherApps 的 getActivityList,後面又會呼叫 callbacks 的 bindAllApplications:

 private void loadAllAppsByBatch() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; ...... mBgAllAppsList.clear(); final int profileCount = profiles.size(); for (int p = 0; p < profileCount; p++) { ...... while (i < N && !mStopped) { if (i == 0) { apps = mLauncherApps.getActivityList(null, user); ...... mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); if (callbacks != null) { if (firstProfile) { callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } } } }); ......

先看 LauncherApps 的 getActivityList,它先用 mService 呼叫 getLauncherActivities 取得 list<ResolveInfo>,再封裝進 ArrayList<LauncherActivityInfo>:

 public List<LauncherActivityInfo> getActivityList(String packageName, UserHandle user) { List<ResolveInfo> activities = null; try { activities = mService.getLauncherActivities(packageName, user); } catch (RemoteException re) { throw new RuntimeException("Failed to call LauncherAppsService"); } if (activities == null) { return Collections.EMPTY_LIST; } ArrayList<LauncherActivityInfo> lais = new ArrayList<LauncherActivityInfo>(); final int count = activities.size(); for (int i = 0; i < count; i++) { ResolveInfo ri = activities.get(i); long firstInstallTime = 0; try { firstInstallTime = mPm.getPackageInfo(ri.activityInfo.packageName, PackageManager.GET_UNINSTALLED_PACKAGES).firstInstallTime; } catch (NameNotFoundException nnfe) { } LauncherActivityInfo lai = new LauncherActivityInfo(mContext, ri, user, firstInstallTime); lais.add(lai); } return lais; }

其 service 是 class LauncherAppsImpl extends ILauncherApps.Stub,下面的 getLauncherActivities 也是透過 PKMS 取得相關 Activity 的 ResolveInfo:

 @Override public List<ResolveInfo> getLauncherActivities(String packageName, UserHandle user) throws RemoteException { ensureInUserProfiles(user, "Cannot retrieve activities for unrelated profile " + user); if (!isUserEnabled(user)) { return new ArrayList<ResolveInfo>(); } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); mainIntent.setPackage(packageName); long ident = Binder.clearCallingIdentity(); try { List<ResolveInfo> apps = mPm.queryIntentActivitiesAsUser(mainIntent, 0, user.getIdentifier()); return apps; } finally { Binder.restoreCallingIdentity(ident); } }

最後回呼 Launcher.java 的 bindAllApplications,在這個函式中就能在桌面上展示系統中所有的應用程式了。

 public void bindAllApplications(final ArrayList<ApplicationInfo> apps) { Runnable setAllAppsRunnable = new Runnable() { public void run() { if (mAppsCustomizeContent != null) { mAppsCustomizeContent.setApps(apps); } } }; View progressBar = mAppsCustomizeTabHost. findViewById(R.id.apps_customize_progress_bar); if (progressBar != null) { ((ViewGroup)progressBar.getParent()).removeView(progressBar); mAppsCustomizeTabHost.post(setAllAppsRunnable); } else { setAllAppsRunnable.run(); } }

三、顯示應用圖示

再看 Launcher 的 onClick 函式,呼叫 showWorkspace 可以顯示所有應用的圖示。

 public void onClick(View v) { if (v.getWindowToken() == null) { return; } if (!mWorkspace.isFinishedSwitchingState()) { return; } Object tag = v.getTag(); if (tag instanceof ShortcutInfo) { final Intent intent = ((ShortcutInfo) tag).intent; int[] pos = new int[2]; v.getLocationOnScreen(pos); intent.setSourceBounds(new Rect(pos[0], pos[1], pos[0] + v.getWidth(), pos[1] + v.getHeight())); boolean success = startActivitySafely(v, intent, tag); if (success && v instanceof BubbleTextView) { mWaitingForResume = (BubbleTextView) v; mWaitingForResume.setStayPressed(true); } } else if (tag instanceof FolderInfo) { if (v instanceof FolderIcon) { FolderIcon fi = (FolderIcon) v; handleFolderClick(fi); } } else if (v == mAllAppsButton) { if (isAllAppsVisible()) { showWorkspace(true); } else { onClickAllAppsButton(v); } } }

在 showWorkspace 中會顯示所有的圖示:

 void showWorkspace(boolean animated, Runnable onCompleteRunnable) { if (mState != State.WORKSPACE) { boolean wasInSpringLoadedMode = (mState == State.APPS_CUSTOMIZE_SPRING_LOADED); mWorkspace.setVisibility(View.VISIBLE); hideAppsCustomizeHelper(State.WORKSPACE, animated, false, onCompleteRunnable); if (mSearchDropTargetBar != null) { mSearchDropTargetBar.showSearchBar(wasInSpringLoadedMode); } showDockDivider(animated && wasInSpringLoadedMode); if (mAllAppsButton != null) { mAllAppsButton.requestFocus(); } } mWorkspace.flashScrollingIndicator(animated); mState = State.WORKSPACE; mUserPresent = true; updateRunning(); getWindow().getDecorView() .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); }

而點擊應用圖示,最終會呼叫 Launcher.java 的 startActivitySafely 來啟動應用,這裡呼叫的 startActivity 就是 Activity 的 startActivity 函式。

 boolean startActivitySafely(View v, Intent intent, Object tag) { boolean success = false; try { success = startActivity(v, intent, tag); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e); } return success; }

以上就是本文的全部內容,希望對大家的學習有所幫助。

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