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

Android Launcher 那點事兒(二):圖標加載、點擊與拖動流程

編輯:關於 Android 程式設計

應朋友要求,這一篇把 Launcher 應用再詳細解說一次,重點放在圖標的加載、點擊啟動與拖動流程。

一、LauncherApplication 中的兩個關鍵成員

先看 LauncherApplication,其中有兩個成員變量對這一講非常重要:

public LauncherModel mModel;
public IconCache mIconCache;

它們在 onCreate() 中被建立:

mIconCache = new IconCache(this);
mModel = new LauncherModel(this, mIconCache);

IconCache 顧名思義是應用圖標的快取;LauncherModel 則是一個 BroadcastReceiver,用來接收應用新增、刪除、變動等廣播並做出響應。在 LauncherModel 的構造函數中會初始化 mAllAppsList(即 AllAppsList),它是存放應用資訊的核心,Launcher 大半操作都圍繞它進行。

AllAppsList 中的關鍵變量:

public ArrayList data = new ArrayList(DEFAULT_APPLICATIONS_NUMBER);      // 所有應用
public ArrayList added = new ArrayList(DEFAULT_APPLICATIONS_NUMBER);     // 自上次 notify 後新增的應用
public ArrayList removed = new ArrayList();                              // 自上次 notify 後刪除的應用
public ArrayList modified = new ArrayList();                             // 自上次 notify 後修改的應用
private IconCache mIconCache;

而 ApplicationInfo 則存放每個應用的資訊:

CharSequence title;      // 應用名稱
Intent intent;           // 啟動應用所用的 Intent
Bitmap iconBitmap;       // 應用圖標的位圖
long firstInstallTime;   // 首次安裝時間
ComponentName componentName;

二、Launcher 的 onCreate

Launcher 是一個 Activity,其 onCreate 中會取得剛才建立的物件:

LauncherApplication app = ((LauncherApplication)getApplication());
mModel = app.setLauncher(this);
mIconCache = app.getIconCache();
mDragController = new DragController(this);

接著如果不是在還原狀態,就會去加載應用:

if (!mRestoring) {
    mModel.startLoader(this, true);
}

startLoader 會啟動一個 LoaderTask 執行緒來加載應用:

public void startLoader(Context context, boolean isLaunching) {
    synchronized (mLock) {
        if (mCallbacks != null && mCallbacks.get() != null) {
            isLaunching = isLaunching || stopLoaderLocked();
            mLoaderTask = new LoaderTask(context, isLaunching);
            sWorkerThread.setPriority(Thread.NORM_PRIORITY);
            sWorker.post(mLoaderTask);
        }
    }
}

三、LoaderTask 的 run():決定加載順序

keep_running: {
    synchronized (mLock) {
        android.os.Process.setThreadPriority(
            mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
    }
    if (loadWorkspaceFirst) {
        loadAndBindWorkspace();
    } else {
        loadAndBindAllApps();
    }
    if (mStopped) break keep_running;
    synchronized (mLock) {
        if (mIsLaunching) {
            android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        }
    }
    waitForIdle();
    if (loadWorkspaceFirst) {
        loadAndBindAllApps();
    } else {
        loadAndBindWorkspace();
    }
    synchronized (mLock) {
        android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
    }
}

這裡決定了先加載 Apps 還是先加載 Workspace。我們只講解 Apps,也就是 loadAndBindAllApps():

private void loadAndBindAllApps() {
    if (!mAllAppsLoaded) {
        loadAllAppsFromPersistence();
        loadAllAppsByBatch();
        synchronized (LoaderTask.this) {
            if (mStopped) return;
            mAllAppsLoaded = true;
        }
    } else {
        onlyBindAllApps();
    }
}

四、loadAllAppsByBatch:分批加載應用

這個方法先取得 Action 為 Intent.ACTION_MAIN、Category 為 Intent.CATEGORY_LAUNCHER 的所有應用,清空 mAllAppsList,再以 PackageManager.queryIntentActivities 查詢:

final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;

mAllAppsList.clear();
apps = packageManager.queryIntentActivities(mainIntent, 0);

接著分批建立 ApplicationInfo:

for (int j=0; i<N && j<batchSize; j++) {
    // 這裡會建立圖標的 bitmap
    mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache, mLabelCache));
    i++;
}

ApplicationInfo 的構造函數會為 componentName、intent、flags、firstInstallTime 賦值,並透過 iconCache.getTitleAndIcon 取得圖標與名稱:

public ApplicationInfo(PackageManager pm, ResolveInfo info, IconCache iconCache,
        HashMap<Object, CharSequence> labelCache) {
    final String packageName = info.activityInfo.applicationInfo.packageName;
    this.componentName = new ComponentName(packageName, info.activityInfo.name);
    this.container = ItemInfo.NO_ID;
    this.setActivity(componentName,
        Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    try {
        int appFlags = pm.getApplicationInfo(packageName, 0).flags;
        if ((appFlags & android.content.pm.ApplicationInfo.FLAG_SYSTEM) == 0) {
            flags |= DOWNLOADED_FLAG;
            if ((appFlags & android.content.pm.ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
                flags |= UPDATED_SYSTEM_APP_FLAG;
            }
        }
        firstInstallTime = pm.getPackageInfo(packageName, 0).firstInstallTime;
    } catch (NameNotFoundException e) {
        Log.d(TAG, "PackageManager.getApplicationInfo failed for " + packageName);
    }
    iconCache.getTitleAndIcon(this, info, labelCache);
}

其中 getTitleAndIcon 會先從快取讀取,若無快取則透過 PackageManager 取得名稱與圖標;getFullResIcon 會取得應用圖標的資源 ID 並回傳 Drawable,若失敗則回傳 framework 中預設的 android 小人圖標(也就是 getFullResDefaultActivityIcon)。若想把 Launcher 圖標換成自訂樣式,就可從這裡動手腳。之後 Utilities.createIconBitmap 會對圖片尺寸做調整,是控制圖標顯示大小與背景的地方。

此外 createBitmap 還有一個巧妙之處——它會針對 com.android.mms 把未讀短信數量畫到圖標上:

public Bitmap createBitmap(ComponentName componentName, Bitmap bitmap, ApplicationInfo application) {
    if (!componentName.getPackageName().equals("com.android.mms")) {
        return bitmap;
    }
    // 回傳帶有未讀提示的 Bitmap
    return MessageManager.getInstance(mContext).createMmsBitmap(bitmap, application);
}

如果想顯示未接來電數量,也可以在此動手腳。

五、把應用綁定到介面

分批建立好 ApplicationInfo 後,透過 mHandler.post 呼叫 callbacks.bindAllApplications 或 bindAppsAdded,最終在 Launcher 的 bindAllApplications 中把應用交給 AppsCustomizePagedView 顯示:

public void setApps(ArrayList list) {
    mApps = list;
    Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
    updatePageCounts();
    LauncherModel.cacheAllApp(mContext, mApps);
    if (testDataReady()) requestLayout();
    invalidatePageData();
}

這裡會重新計算頁數、把應用資訊備份到資料庫(加快開機載入),並更新佈局把圖標顯示出來。invalidatePageData() 則負責在頁面放滿時新增一頁。

六、點擊圖標啟動應用

點擊待機(Workspace)圖標的事件在 Launcher 的 onClick 中處理,它從 tag 取出 ShortcutInfo,再用其 intent 啟動應用:

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(intent, tag);
    ...
}

點擊主菜單圖標則在 AppsCustomizePagedView 中處理,同樣是取出 ApplicationInfo 並用其 intent 啟動。

七、拖動圖標

長按待機圖標會觸發 onLongClick,最終呼叫 mWorkspace.startDrag:

void startDrag(CellLayout.CellInfo cellInfo) {
    View child = cellInfo.cell;
    if (!child.isInTouchMode()) return;
    mDragInfo = cellInfo;
    child.setVisibility(GONE);
    child.clearFocus();
    child.setPressed(false);
    final Canvas canvas = new Canvas();
    final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
    mDragOutline = createDragOutline(child, canvas, bitmapPadding);
    beginDragShared(child, this);
}

beginDragShared 會建立一張帶透明與縮放效果的拖動 Bitmap,並交由 mDragController.startDrag 建立 DragView 顯示;長按時的震動回饋就在此處(mVibrator.vibrate)。之後透過 handleMoveEvent 不斷更新座標與偵測放置目標,直到 ACTION_UP 時呼叫 drop 完成放下:

private void drop(float x, float y) {
    final int[] coordinates = mCoordinatesTemp;
    final DropTarget dropTarget = findDropTarget((int) x, (int) y, coordinates);
    mDragObject.x = coordinates[0];
    mDragObject.y = coordinates[1];
    boolean accepted = false;
    if (dropTarget != null) {
        mDragObject.dragComplete = true;
        dropTarget.onDragExit(mDragObject);
        if (dropTarget.acceptDrop(mDragObject)) {
            dropTarget.onDrop(mDragObject);
            accepted = true;
        }
    }
    mDragObject.dragSource.onDropCompleted((View) dropTarget, mDragObject, accepted);
}

Workspace 的 onDrop 依來源分為幾種情況:從主菜單拖來會走 onDropExternal;在待機內拖動則視是否跨頁,透過 addInScreen 把 view 加入對應的 CellLayout,最終呼叫 mChildren.addView 完成擺放,並更新資料庫中的位置。

這一篇講解了 Launcher 圖標的加載、點擊啟動與拖動流程;至於安裝、卸載、更新應用、壁紙與 widget 等內容,若有需要再另行說明。

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