0
点赞
收藏
分享

微信扫一扫

Launcher3 安装App加载显示过程分析,靠着这份190页的面试资料

彪悍的鼹鼠 2022-02-17 阅读 86

synchronized (this) {

for (LauncherActivityInfo info : apps) {

if(DmConfig.isHiddenPackage(info.getComponentName())){continue;}//hide app by lhw

for (AppInfo appInfo : appsList.added) {

if(info.getComponentName().equals(appInfo.componentName)){

InstallShortcutReceiver.PendingInstallShortcutInfo mPendingInstallShortcutInfo

= new InstallShortcutReceiver.PendingInstallShortcutInfo(info,context);

added.add(mPendingInstallShortcutInfo);

installQueue.add(mPendingInstallShortcutInfo.getItemInfo());

}

}

}

}

}

if (!added.isEmpty()) {

app.getModel().addAndBindAddedWorkspaceItems(installQueue);

}

}

//add for load new install app on workspace end by lhw

appsList.added.clear();

addedOrModified.addAll(appsList.modified);

appsList.modified.clear();

final ArrayList removedApps = new ArrayList<>(appsList.removed);

appsList.removed.clear();

final ArrayMap<ComponentName, AppInfo> addedOrUpdatedApps = new ArrayMap<>();

if (!addedOrModified.isEmpty()) {

scheduleCallbackTask(new CallbackTask() {

@Override

public void execute(Callbacks callbacks) {

//TODO bindAppsAddedOrUpdated 通过AllAppsStore的addOrUpdateApps方法去通知AllApps界面刷新 LHW

callbacks.bindAppsAddedOrUpdated(addedOrModified);

}

});

for (AppInfo ai : addedOrModified) {

addedOrUpdatedApps.put(ai.componentName, ai);

}

}

  • 通过execute 执行应用的添加 删除 更新操作
  1. iconCache.updateIconsForPkg 更新应用图标信息

/**

  • Updates the entries related to the given package in memory and persistent DB.

*/

public synchronized void updateIconsForPkg(String packageName, UserHandle user) {

removeIconsForPkg(packageName, user);

try {

PackageInfo info = mPackageManager.getPackageInfo(packageName,

PackageManager.GET_UNINSTALLED_PACKAGES);

long userSerial = mUserManager.getSerialNumberForUser(user);

for (LauncherActivityInfo app : mLauncherApps.getActivityList(packageName, user)) {

addIconToDBAndMemCache(app, info, userSerial, false /replace existing/);

}

} catch (NameNotFoundException e) {

Log.d(TAG, “Package not found”, e);

}

}

  1. 通过appsList.addPackage方法将新应用信息缓存到AllAppsList

/**

  • Add the icons for the supplied apk called packageName.

*/

public void addPackage(Context context, String packageName, UserHandle user) {

final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);

final List matches = launcherApps.getActivityList(packageName,

user);

for (LauncherActivityInfo info : matches) {

add(new AppInfo(context, info, user), info);

}

}

/**

  • Add the supplied ApplicationInfo objects to the list, and enqueue it into the

  • list to broadcast when notify() is called.

  • If the app is already in the list, doesn’t add it.

*/

public void add(AppInfo info, LauncherActivityInfo activityInfo) {

if (!mAppFilter.shouldShowApp(info.componentName)) {

return;

}

if (findAppInfo(info.componentName, info.user) != null) {

return;

}

mIconCache.getTitleAndIcon(info, activityInfo, true /* useLowResIcon */);

data.add(info);

added.add(info);

}

  1. 通过bindAppsAddedOrUpdated方法回调launcher,进行界面更新的处理。

final ArrayMap<ComponentName, AppInfo> addedOrUpdatedApps = new ArrayMap<>();

if (!addedOrModified.isEmpty()) {

scheduleCallbackTask(new CallbackTask() {

@Override

public void execute(Callbacks callbacks) {//TODO bindAppsAddedOrUpdated 通过AllAppsStore的addOrUpdateApps方法去通知AllApps界面刷新 LHW

callbacks.bindAppsAddedOrUpdated(addedOrModified);

}

});

for (AppInfo ai : addedOrModified) {

addedOrUpdatedApps.put(ai.componentName, ai);

}

}

4.Launcher.java 中通过AllAppsStore的addOrUpdateApps方法去通知AllApps界面刷新

/**

  • Default launcher application.

*/

public class Launcher extends BaseDraggingActivity implements LauncherExterns,

LauncherModel.Callbacks, LauncherProviderChangeListener, UserEventDelegate{

public static final String TAG = “Launcher”;

/**

  • A package was updated.

  • Implementation of the method from LauncherModel.Callbacks.

*/

@Override

public void bindAppsAddedOrUpdated(ArrayList apps) {

mAppsView.getAppsStore().addOrUpdateApps(apps);

}

5.在AllAppsStore中更新App 列表

/**

  • A utility class to maintain the collection of all apps.

*/

public class AllAppsStore {

/**

  • Adds or updates existing apps in the list

*/

public void addOrUpdateApps(List apps) {

for (AppInfo app : apps) {

Log.d(“LHW_L”,“addOrUpdateApps-==”+app.title+",=apps.size="+apps.size());

mComponentToAppMap.put(app.toComponentKey(), app);

}

notifyUpdate();

}

  1. AllAppsContainerView 获取 AllAppsStore 所有应用数据,通过all_apps_rv_layout.xml中AllAppsRecyclerView显示

/**

  • The all apps view container.

*/

public class AllAppsContainerView extends SpringRelativeLayout implements DragSource,

Insettable, OnDeviceProfileChangeListener {

private final AllAppsStore mAllAppsStore = new AllAppsStore();

public AllAppsContainerView(Context context, AttributeSet attrs, int defStyleAttr) {

super(context, attrs, defStyleAttr);

mLauncher = Launcher.getLauncher(context);

mLauncher.addOnDeviceProfileChangeListener(this);

mSearchQueryBuilder = new SpannableStringBuilder();

Selection.setSelection(mSearchQueryBuilder, 0);

mAH = new AdapterHolder[2];

mAH[AdapterHolder.MAIN] = new AdapterHolder(false /* isWork */);

mAH[AdapterHolder.WORK] = new AdapterHolder(true /* isWork */);

mNavBarScrimPaint = new Paint();

mNavBarScrimPaint.setColor(Themes.getAttrColor(context, R.attr.allAppsNavBarScrimColor));

mAllAppsStore.addUpdateListener(this::onAppsUpdated);

addSpringView(R.id.all_apps_header);

addSpringView(R.id.apps_list_view);

addSpringView(R.id.all_apps_tabs_view_pager);

}

  1. AllAppsContainerView中 AdapterHolderAllAppsGridAdapter加载 显示所有App信息到视图

/**

  • A RecyclerView with custom fast scroll support for the all apps view.

*/

public class AllAppsRecyclerView extends BaseRecyclerView implements LogContainerProvider {

public class AdapterHolder {

public static final int MAIN = 0;

public static final int WORK = 1;

public final AllAppsGridAdapter adapter;

final LinearLayoutManager layoutManager;

final AlphabeticalAppsList appsList;

final Rect padding = new Rect();

AllAppsRecyclerView recyclerView;

boolean verticalFadingEdge;

AdapterHolder(boolean isWork) {

appsList = new AlphabeticalAppsList(mLauncher, mAllAppsStore, isWork);

adapter = new AllAppsGridAdapter(mLauncher, appsList);

appsList.setAdapter(adapter);

layoutManager = adapter.getLayoutManager();

}

void setup(@NonNull View rv, @Nullable ItemInfoMatcher matcher) {

appsList.updateItemFilter(matcher);

recyclerView = (AllAppsRecyclerView) rv;

recyclerView.setEdgeEffectFactory(createEdgeEffectFactory());

recyclerView.setApps(appsList, mUsingTabs);

recyclerView.setLayoutManager(layoutManager);

recyclerView.setAdapter(adapter);

recyclerView.setHasFixedSize(true);

// No animations will occur when changes occur to the items in this RecyclerView.

recyclerView.setItemAnimator(null);

FocusedItemDecorator focusedItemDecorator = new FocusedItemDecorator(recyclerView);

recyclerView.addItemDecoration(focusedItemDecorator);

adapter.setIconFocusListener(focusedItemDecorator.getFocusListener());

applyVerticalFadingEdgeEnabled(verticalFadingEdge);

applyPadding();

}

  1. AllAppsGridAdapter 获取数据显示App 图标和信息

@Override

public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

switch (viewType) {

case VIEW_TYPE_ICON:

BubbleTextView icon = (BubbleTextView) mLayoutInflater.inflate(

R.layout.all_apps_icon, parent, false);

icon.setOnClickListener(ItemClickHandler.INSTANCE);

icon.setOnLongClickListener(ItemLongClickListener.INSTANCE_ALL_APPS);

icon.setLongPressTimeout(ViewConfiguration.getLongPressTimeout());

icon.setOnFocusChangeListener(mIconFocusListener);

// Ensure the all apps icon height matches the workspace icons in portrait mode.

icon.getLayoutParams().height = mLauncher.getDeviceProfile().allAppsCellHeightPx;

return new ViewHolder(icon);

<com.android.launcher3.BubbleTextView

xmlns:android=“http://schemas.android.com/apk/res/android”

xmlns:launcher=“http://schemas.android.com/apk/res-auto”

style="@style/BaseIcon"

android:id="@+id/icon"

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:stateListAnimator="@animator/all_apps_fastscroll_icon_anim"

launcher:iconDisplay=“all_apps”

launcher:centerVertically=“true”

android:paddingLeft="@dimen/dynamic_grid_cell_padding_x"

android:paddingRight="@dimen/dynamic_grid_cell_padding_x" />

@Override

public void onBindViewHolder(ViewHolder holder, int position) {

switch (holder.getItemViewType()) {

case VIEW_TYPE_ICON:

AppInfo info = mApps.getAdapterItems().get(position).appInfo;

BubbleTextView icon = (BubbleTextView) holder.itemView;

icon.reset();

icon.applyFromApplicationInfo(info);

break;

/**

  • TextView that draws a bubble behind the text. We cannot use a LineBackgroundSpan

  • because we want to make the bubble taller than the text and TextView’s clip is

  • too aggressive.

*/

public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, OnResumeCallback {

public void applyFromApplicationInfo(AppInfo info) {

applyIconAndLabel(info);

// We don’t need to check the info since it’s not a ShortcutInfo

super.setTag(info);

// Verify high res immediately

verifyHighRes();

if (info instanceof PromiseAppInfo) {

PromiseAppInfo promiseAppInfo = (PromiseAppInfo) info;

applyProgressLevel(promiseAppInfo.level);

}

applyBadgeState(info, false /* animate */);

}

private void applyIconAndLabel(ItemInfoWithIcon info) {

FastBitmapDrawable iconDrawable = DrawableFactory.get(getContext()).newIcon(info);

mBadgeColor = IconPalette.getMutedColor(info.iconColor, 0.54f);

setIcon(iconDrawable);

setText(info.title);

if (info.contentDescription != null) {

setContentDescription(info.isDisabled()

? getContext().getString(R.string.disabled_app_label, info.contentDescription)
info.contentDescription);

}

}

/**

  • Sets the icon for this view based on the layout direction.

*/

private void setIcon(Drawable icon) {

if (mIsIconVisible) {

applyCompoundDrawables(icon);

}

mIcon = icon;

}

protected void applyCompoundDrawables(Drawable icon) {

// If we had already set an icon before, disable relayout as the icon size is the

// same as before.

mDisableRelayout = mIcon != null;

icon.setBounds(0, 0, mIconSize, mIconSize);

if (mLayoutHorizontal) {

setCompoundDrawablesRelative(icon, null, null, null);

} else {

setCompoundDrawables(null, icon, null, null);

}

mDisableRelayout = false;

}

Launcher 初始加载所有应用信息

/**

  • Default launcher application.

*/

public class Launcher extends BaseDraggingActivity implements LauncherExterns,

LauncherModel.Callbacks, LauncherProviderChangeListener, UserEventDelegate{

public static final String TAG = “Launcher”;

static final boolean LOGD = false;

@Override

protected void onCreate(Bundle savedInstanceState) {

TraceHelper.beginSection(“Launcher-onCreate”);

super.onCreate(savedInstanceState);

TraceHelper.partitionSection(“Launcher-onCreate”, “super call”);

LauncherAppState app = LauncherAppState.getInstance(this);

mOldConfig = new Configuration(getResources().getConfiguration());

//获取初始化 LauncherModel 进行广播监听数据绑定和更新加载

mModel = app.setLauncher(this);

initDeviceProfile(app.getInvariantDeviceProfile());

// We only load the page synchronously if the user rotates (or triggers a

// configuration change) while launcher is in the foreground

int currentScreen = PagedView.INVALID_RESTORE_PAGE;

if (savedInstanceState != null) {

currentScreen = savedInstanceState.getInt(RUNTIME_STATE_CURRENT_SCREEN, currentScreen);

}

// LauncherModel startLoader 开启线程进行数据加载

if (!mModel.startLoader(currentScreen)) {

if (!internalStateHandled) {

// If we are not binding synchronously, show a fade in animation when

// the first page bind completes.

mDragLayer.getAlphaProperty(ALPHA_INDEX_LAUNCHER_LOAD).setValue(0);

}

} else {

// Pages bound synchronously.

mWorkspace.setCurrentPage(currentScreen);

setWorkspaceLoading(true);

}

// For handling default keys

setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);

setContentView(mLauncherView);

LauncherModel 广播监听Launcher数据处理和接口回调

/**

  • Maintains in-memory state of the Launcher. It is expected that there should be only one

  • LauncherModel object held in a static. Also provide APIs for updating the database state

  • for the Launcher.

*/

public class LauncherModel extends BroadcastReceiver

implements LauncherAppsCompat.OnAppsChangedCallbackCompat {

private static final boolean DEBUG_RECEIVER = !com.android.launcher3.Log.IS_USER_VERSON;//true;

/**

  • Starts the loader. Tries to bind {@params synchronousBindPage} synchronously if possible.

  • @return true if the page could be bound synchronously.

*/

public boolean startLoader(int synchronousBindPage) {

// Enable queue before starting loader. It will get disabled in Launcher#finishBindingItems

InstallShortcutReceiver.enableInstallQueue(InstallShortcutReceiver.FLAG_LOADER_RUNNING);

synchronized (mLock) {

// Don’t bother to start the thread if we know it’s not going to do anything

if (mCallbacks != null && mCallbacks.get() != null) {

final Callbacks oldCallbacks = mCallbacks.get();

// Clear any pending bind-runnables from the synchronized load process.

// begin modify by mjf for REQ006

//mUiExecutor.execute(oldCallbacks::clearPendingBinds);

final Runnable runnable = new Runnable() {

@Override

public void run() {

oldCallbacks.clearPendingBinds();

}

};

mUiExecutor.execute(runnable);

// end

// If there is already one running, tell it to stop.

stopLoader();

LoaderResults loaderResults = new LoaderResults(mApp, sBgDataModel,

mBgAllAppsList, synchronousBindPage, mCallbacks);

if (mModelLoaded && !mIsLoaderTaskRunning) {

// Divide the set of loaded items into those that we are binding synchronously,

// and everything else that is to be bound normally (asynchronously).

loaderResults.bindWorkspace();

// For now, continue posting the binding of AllApps as there are other

// issues that arise from that.

loaderResults.bindAllApps();

loaderResults.bindDeepShortcuts();

loaderResults.bindWidgets();

return true;

} else {

startLoaderForResults(loaderResults);

}

}

}

return false;

}

  • startLoaderForResults() 开始加载和返回数据结果

public void startLoaderForResults(LoaderResults results) {

synchronized (mLock) {

stopLoader();

mLoaderTask = new LoaderTask(mApp, mBgAllAppsList, sBgDataModel, results);

runOnWorkerThread(mLoaderTask);

onPackageChanged(DmConfig.mCalenderPkgName, android.os.Process.myUserHandle()); /* add by mjf for HCT_CUSTOM_CALENDAR */

}

}

public void startLoaderForResultsIfNotLoaded(LoaderResults results) {

synchronized (mLock) {

if (!isModelLoaded()) {

Log.d(TAG, “Workspace not loaded, loading now”);

startLoaderForResults(results);

}

}

}

  • LoaderTask.java 启动线程去处理桌面数据显示信息,所有桌面图标、组件、文件夹等信息

/**

  • Runnable for the thread that loads the contents of the launcher:

    • workspace icons
    • widgets
    • all apps icons
    • deep shortcuts within apps

*/

public class LoaderTask implements Runnable {

private static final String TAG = “LoaderTask”;

public LoaderTask(LauncherAppState app, AllAppsList bgAllAppsList, BgDataModel dataModel,

LoaderResults results) {

mApp = app;

mBgAllAppsList = bgAllAppsList;

mBgDataModel = dataModel;

学习福利

【Android 详细知识点思维脑图(技能树)】

其实Android开发的知识点就那么多,面试问来问去还是那么点东西。所以面试没有其他的诀窍,只看你对这些知识点准备的充分程度。so,出去面试时先看看自己复习到了哪个阶段就好。

虽然 Android 没有前几年火热了,已经过去了会四大组件就能找到高薪职位的时代了。这只能说明 Android 中级以下的岗位饱和了,现在高级工程师还是比较缺少的,很多高级职位给的薪资真的特别高(钱多也不一定能找到合适的),所以努力让自己成为高级工程师才是最重要的。

由于篇幅有限,这里以图片的形式给大家展示一小部分。

详细整理在GitHub点击可见;

Android架构视频+BAT面试专题PDF+学习笔记

网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。

ivate static final String TAG = “LoaderTask”;

public LoaderTask(LauncherAppState app, AllAppsList bgAllAppsList, BgDataModel dataModel,

LoaderResults results) {

mApp = app;

mBgAllAppsList = bgAllAppsList;

mBgDataModel = dataModel;

学习福利

【Android 详细知识点思维脑图(技能树)】

其实Android开发的知识点就那么多,面试问来问去还是那么点东西。所以面试没有其他的诀窍,只看你对这些知识点准备的充分程度。so,出去面试时先看看自己复习到了哪个阶段就好。

虽然 Android 没有前几年火热了,已经过去了会四大组件就能找到高薪职位的时代了。这只能说明 Android 中级以下的岗位饱和了,现在高级工程师还是比较缺少的,很多高级职位给的薪资真的特别高(钱多也不一定能找到合适的),所以努力让自己成为高级工程师才是最重要的。

由于篇幅有限,这里以图片的形式给大家展示一小部分。

[外链图片转存中…(img-M1AHQvPD-1645107954510)]

详细整理在GitHub点击可见;

Android架构视频+BAT面试专题PDF+学习笔记

网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。

举报

相关推荐

0 条评论