墨香帶你學Launcher之(八)- 加載Icon、設置壁紙

上一章墨香帶你學Launcher之(七)- 小部件的加載、添加以及大小調節介紹了小部件的加載以及添加過程,基於個人計劃對於Launcher的講解基本要完成了,所以本篇是我對Launcher講解的最後一部分,計劃了好久,由於時間的問題一直沒有寫,今天趁着有空寫完。寫了八篇,很少,Launcher裏面還有不少東西,有興趣的能夠本身繼續研究,看完這些主要的其餘都是問題了,有什麼須要瞭解的能夠留言。最新版的Launcher代碼我已經放到github上,想看的本身能夠去下載。java

加載Icon

對於Icon的操做其實主要是加載、更新以及刪除,加載主要是啓動Launcher、安裝應用,更新是在更新應用時更新Icon、刪除是卸載應用時會刪除Icon,所以咱們能夠從這幾方面分析Icon的處理。git

Launcher啓動時Icon加載

Launcher的數據加載流程我在第二篇墨香帶你學Launcher之(二)- 數據加載流程講過,不熟悉的能夠去看看。首先是將xml文件中配置的Apk信息解析保存到數據庫,而後讀取數據庫,查看手機中是否存在該apk,若是有加載相關信息,加載流程在「loadWorkspace」方法中,在加載過程當中會去生成對應的Icon,咱們看一下代碼:github

if (itemReplaced) {
    ...
        info = getAppShortcutInfo(manager, intent, user, context, null,
                cursorIconInfo.iconIndex, titleIndex,
                false, useLowResIcon);
    ...
} else if (restored) {
    ...
        info = getRestoredItemInfo(c, titleIndex, intent,
                promiseType, itemType, cursorIconInfo, context);
    ...                                   
} else if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
    info = getAppShortcutInfo(manager, intent, user, context, c,
            cursorIconInfo.iconIndex, titleIndex,
            allowMissingTarget, useLowResIcon);
} else {
    info = getShortcutInfo(c, context, titleIndex, cursorIconInfo);
    ...
}複製代碼

在段代碼中主要有三個方法涉及到加載Icon,getAppShortcutInfo、getRestoredItemInfo以及getShortcutInfo方法,咱們看看這個三個方法的代碼:數據庫

第一個:數組

public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent, UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex, boolean allowMissingTarget, boolean useLowResIcon) {

        ...

        final ShortcutInfo info = new ShortcutInfo();
        mIconCache.getTitleAndIcon(info, componentName, lai, user, false, useLowResIcon);
        if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) {
            Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context);
            info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon);
        }

        ...
    }複製代碼

在這段代碼中主要是調用IconCache中的getTitleAndIcon方法,這個方法詳細過程咱們一會再看,而後判斷是不是默認圖標,若是是生成Icon圖標,若是能生成則設置圖標,若是不能生成則採用默認圖標。Utilities.createIconBitmap代碼不在詳細講,看看就會了。promise

咱們接着看第二個方法:緩存

public ShortcutInfo getRestoredItemInfo(Cursor c, int titleIndex, Intent intent, int promiseType, int itemType, CursorIconInfo iconInfo, Context context) {
        ...

        Bitmap icon = iconInfo.loadIcon(c, info, context);
        // the fallback icon
        if (icon == null) {
            mIconCache.getTitleAndIcon(info, intent, info.user, false /* useLowResIcon */);
        } else {
            info.setIcon(icon);
        }

        ...
    }複製代碼

這個方法中主要是調用CursorIconInfo中的loadIcon方法,代碼咱們一會再看,若是能獲取到Icon則設置這個Icon,若是不能則經過IconCache.getTitleAndIcon方法獲取,和上面同樣了。微信

第三個方法:app

ShortcutInfo getShortcutInfo(Cursor c, Context context, int titleIndex, CursorIconInfo iconInfo) {
        ...

        Bitmap icon = iconInfo.loadIcon(c, info, context);
        // the fallback icon
        if (icon == null) {
            icon = mIconCache.getDefaultIcon(info.user);
            info.usingFallbackIcon = true;
        }
        info.setIcon(icon);
        return info;
    }複製代碼

這個方法中仍是調用CursorIconInfo中的loadIcon方法,若是能獲取,則設置圖標,若是不能獲取默認圖標設置。從上面三個方法代碼看其實最終調用了兩個方法,一個是IconCache.getTitleAndIcon方法,一個是CursorIconInfo.loadIcon方法。異步

咱們先看一下CursorIconInfo.loadIcon代碼:

public Bitmap loadIcon(Cursor c, ShortcutInfo info, Context context) {
        Bitmap icon = null;
        int iconType = c.getInt(iconTypeIndex);
        switch (iconType) {
        case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
            String packageName = c.getString(iconPackageIndex);
            String resourceName = c.getString(iconResourceIndex);
            if (!TextUtils.isEmpty(packageName) || !TextUtils.isEmpty(resourceName)) {
                info.iconResource = new ShortcutIconResource();
                info.iconResource.packageName = packageName;
                info.iconResource.resourceName = resourceName;
                icon = Utilities.createIconBitmap(packageName, resourceName, context);
            }
            if (icon == null) {
                // Failed to load from resource, try loading from DB.
                icon = Utilities.createIconBitmap(c, iconIndex, context);
            }
            break;
        case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
            icon = Utilities.createIconBitmap(c, iconIndex, context);
            info.customIcon = icon != null;
            break;
        }
        return icon;
    }複製代碼

在這個方法中首先是從資源獲取,若是獲取不到,則從數據庫獲取,及Utilities.createIconBitmap(packageName, resourceName, context)和Utilities.createIconBitmap(c, iconIndex, context),咱們看看這兩個方法:

第一個方法:

public static Bitmap createIconBitmap(String packageName, String resourceName, Context context) {
        PackageManager packageManager = context.getPackageManager();
        // the resource
        try {
            Resources resources = packageManager.getResourcesForApplication(packageName);
            if (resources != null) {
                final int id = resources.getIdentifier(resourceName, null, null);
                return createIconBitmap(
                        resources.getDrawableForDensity(id, LauncherAppState.getInstance()
                                .getInvariantDeviceProfile().fillResIconDpi), context);
            }
        } catch (Exception e) {
            // Icon not found.
        }
        return null;
    }複製代碼

這個方法是根據包名獲取id,而後根據id獲取drawable,由drawable生產Bitmap。

第二個方法:

public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
        byte[] data = c.getBlob(iconIndex);
        try {
            return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
        } catch (Exception e) {
            return null;
        }
    }複製代碼

從數據庫讀取Icon的byte數據,而後生成圖片。這樣看就很清楚這個方法加載Icon的過程了。那麼數據庫中的Icon怎麼來的咱們回到前面再看IconCache.getTitleAndIcon方法:

public synchronized void getTitleAndIcon( ShortcutInfo shortcutInfo, ComponentName component, LauncherActivityInfoCompat info, UserHandleCompat user, boolean usePkgIcon, boolean useLowResIcon) {
        CacheEntry entry = cacheLocked(component, info, user, usePkgIcon, useLowResIcon);
        shortcutInfo.setIcon(getNonNullIcon(entry, user));
        shortcutInfo.title = Utilities.trim(entry.title);
        shortcutInfo.usingFallbackIcon = isDefaultIcon(entry.icon, user);
        shortcutInfo.usingLowResIcon = entry.isLowResIcon;
    }複製代碼

咱們看到了setIcon方法,那麼是getNonNullIcon這個方法建立了Icon,這個方法有個咱們不熟悉的對象entry,向上看這個entry是子啊上面經過cacheLocked方法建立的,咱們跟蹤一下這個方法:

private CacheEntry cacheLocked(ComponentName componentName, LauncherActivityInfoCompat info, UserHandleCompat user, boolean usePackageIcon, boolean useLowResIcon) {
        ComponentKey cacheKey = new ComponentKey(componentName, user);
        CacheEntry entry = mCache.get(cacheKey);
        if (entry == null || (entry.isLowResIcon && !useLowResIcon)) {
            entry = new CacheEntry();
            mCache.put(cacheKey, entry);

            // Check the DB first.
            if (!getEntryFromDB(cacheKey, entry, useLowResIcon)) {
                if (info != null) {
                    entry.icon = Utilities.createIconBitmap(info.getBadgedIcon(mIconDpi), mContext);
                } else {
                    if (usePackageIcon) {
                        CacheEntry packageEntry = getEntryForPackageLocked(
                                componentName.getPackageName(), user, false);
                        if (packageEntry != null) {
                            if (DEBUG) Log.d(TAG, "using package default icon for " +
                                    componentName.toShortString());
                            entry.icon = packageEntry.icon;
                            entry.title = packageEntry.title;
                            entry.contentDescription = packageEntry.contentDescription;
                        }
                    }
                    if (entry.icon == null) {
                        entry.icon = getDefaultIcon(user);
                    }
                }
            }
            ...

        }
        return entry;
    }複製代碼

首先是從mCache中獲取,若是存在CacheEntry對象,則不須要再建立,若是沒有則要建立改對象,而後加載到mCache中,而後經過調用getEntryFromDB方法從數據庫查詢是否有改對象信息,若是沒有則要建立對應Icon,咱們先看看getEntryFromDB這個方法:

private boolean getEntryFromDB(ComponentKey cacheKey, CacheEntry entry, boolean lowRes) {
        ...
        try {
            if (c.moveToNext()) {
                entry.icon = loadIconNoResize(c, 0, lowRes ? mLowResOptions : null);
                entry.isLowResIcon = lowRes;
                ...
            }
        } finally {
            c.close();
        }
        return false;
    }複製代碼

該方法經過查詢數據庫來生成Icon,調用方法loadIconNoResize,看代碼:

private static Bitmap loadIconNoResize(Cursor c, int iconIndex, BitmapFactory.Options options) {
        byte[] data = c.getBlob(iconIndex);
        try {
            return BitmapFactory.decodeByteArray(data, 0, data.length, options);
        } catch (Exception e) {
            return null;
        }
    }複製代碼

和上面的同樣,就不用講了。

回到cacheLocked方法中,若是數據庫中沒有,要繼續建立Icon,首先判斷LauncherActivityInfoCompat是否爲空,調用Utilities.createIconBitmap方法獲取Icon,代碼就不貼了,也不難,若是爲空的話會判斷usePackageIcon(根據包名獲取Icon),若是用的話則會調用getEntryForPackageLocked方法獲取CacheEntry,看代碼:

private CacheEntry getEntryForPackageLocked(String packageName, UserHandleCompat user, boolean useLowResIcon) {
        ComponentKey cacheKey = getPackageKey(packageName, user);
        CacheEntry entry = mCache.get(cacheKey);

        if (entry == null || (entry.isLowResIcon && !useLowResIcon)) {
            entry = new CacheEntry();
            boolean entryUpdated = true;

            // Check the DB first.
            if (!getEntryFromDB(cacheKey, entry, useLowResIcon)) {
                try {
                    ...
                    Drawable drawable = mUserManager.getBadgedDrawableForUser(
                            appInfo.loadIcon(mPackageManager), user);
                    entry.icon = Utilities.createIconBitmap(drawable, mContext);
                    entry.title = appInfo.loadLabel(mPackageManager);
                    entry.contentDescription = mUserManager.getBadgedLabelForUser(entry.title, user);
                    entry.isLowResIcon = false;

                    // Add the icon in the DB here, since these do not get written during
                    // package updates.
                    ContentValues values =
                            newContentValues(entry.icon, entry.title.toString(), mPackageBgColor);
                    addIconToDB(values, cacheKey.componentName, info,
                            mUserManager.getSerialNumberForUser(user));

                } catch (NameNotFoundException e) {
                    if (DEBUG) Log.d(TAG, "Application not installed " + packageName);
                    entryUpdated = false;
                }
            }

            // Only add a filled-out entry to the cache
            if (entryUpdated) {
                mCache.put(cacheKey, entry);
            }
        }
        return entry;
    }複製代碼

代碼和cacheLocked方法很像,也是先判斷數據庫中是否存在,不存在就要加載,這裏有個方法addIconToDB,看上面ContentValues的註釋,就是把Icon存到數據庫中,原來是在這裏存入數據庫的,其實Icon的信息首先放入ContentValues中,而後存入數據庫,咱們看看代碼:

private ContentValues newContentValues(Bitmap icon, String label, int lowResBackgroundColor) {
        ContentValues values = new ContentValues();
        values.put(IconDB.COLUMN_ICON, Utilities.flattenBitmap(icon));

        values.put(IconDB.COLUMN_LABEL, label);
        values.put(IconDB.COLUMN_SYSTEM_STATE, mSystemState);

        if (lowResBackgroundColor == Color.TRANSPARENT) {
          values.put(IconDB.COLUMN_ICON_LOW_RES, Utilities.flattenBitmap(
          Bitmap.createScaledBitmap(icon,
                  icon.getWidth() / LOW_RES_SCALE_FACTOR,
                  icon.getHeight() / LOW_RES_SCALE_FACTOR, true)));
        } else {
            synchronized (this) {
                if (mLowResBitmap == null) {
                    mLowResBitmap = Bitmap.createBitmap(icon.getWidth() / LOW_RES_SCALE_FACTOR,
                            icon.getHeight() / LOW_RES_SCALE_FACTOR, Bitmap.Config.RGB_565);
                    mLowResCanvas = new Canvas(mLowResBitmap);
                    mLowResPaint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);
                }
                mLowResCanvas.drawColor(lowResBackgroundColor);
                mLowResCanvas.drawBitmap(icon, new Rect(0, 0, icon.getWidth(), icon.getHeight()),
                        new Rect(0, 0, mLowResBitmap.getWidth(), mLowResBitmap.getHeight()),
                        mLowResPaint);
                values.put(IconDB.COLUMN_ICON_LOW_RES, Utilities.flattenBitmap(mLowResBitmap));
            }
        }
        return values;
    }複製代碼

經過Utilities.flattenBitmap(icon)方法將Icon轉換成byte數組而後存入數據庫。再回到cacheLocked方法中,若是仍是沒有獲取到Icon,那麼只能獲取系統默認Icon了,也就是咱們本身寫app的默認Icon圖標(機器人圖標)。這個是咱們加載配置文件中的Apk信息時加載Icon的過程,咱們再看看加載全部app時是否是也是這樣,咱們先看加載方法loadAllApps代碼:

private void loadAllApps() {
            ...

                // Create the ApplicationInfos
                for (int i = 0; i < apps.size(); i++) {
                    LauncherActivityInfoCompat app = apps.get(i);
                    // This builds the icon bitmaps.
                    mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache));
                }

            ...        
    }複製代碼

咱們看到主要是AppInfo對象的生成,咱們看看代碼:

public AppInfo(Context context, LauncherActivityInfoCompat info, UserHandleCompat user, IconCache iconCache) {
        this.componentName = info.getComponentName();
        this.container = ItemInfo.NO_ID;

        flags = initFlags(info);
        firstInstallTime = info.getFirstInstallTime();
        iconCache.getTitleAndIcon(this, info, true /* useLowResIcon */);
        intent = makeLaunchIntent(context, info, user);
        this.user = user;
    }複製代碼

從上面代碼咱們看到其實仍是調用getTitleAndIcon方法,又回到咱們上面講的過程了。

APK安裝、更新、卸載時Icon處理

APK的安裝、卸載、更新、可用以及不可用在墨香帶你學Launcher之(四)-應用安裝、更新、卸載時的數據加載中講到過,不清楚的能夠去看看,這幾個實現方法是在LauncherModel中來處理的:

@Override
    public void onPackageChanged(String packageName, UserHandleCompat user) {
        int op = PackageUpdatedTask.OP_UPDATE;
        enqueuePackageUpdated(new PackageUpdatedTask(op, new String[]{packageName},
                user));
    }

    @Override
    public void onPackageRemoved(String packageName, UserHandleCompat user) {
        int op = PackageUpdatedTask.OP_REMOVE;
        enqueuePackageUpdated(new PackageUpdatedTask(op, new String[]{packageName},
                user));
    }

    @Override
    public void onPackageAdded(String packageName, UserHandleCompat user) {
        int op = PackageUpdatedTask.OP_ADD;
        enqueuePackageUpdated(new PackageUpdatedTask(op, new String[]{packageName},
                user));
    }

    @Override
    public void onPackagesAvailable(String[] packageNames, UserHandleCompat user, boolean replacing) {
        if (!replacing) {
            enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
                    user));
            if (mAppsCanBeOnRemoveableStorage) {
                startLoaderFromBackground();
            }
        } else {
            // If we are replacing then just update the packages in the list
            enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
                    packageNames, user));
        }
    }

    @Override
    public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user, boolean replacing) {
        if (!replacing) {
            enqueuePackageUpdated(new PackageUpdatedTask(
                    PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
                    user));
        }
    }複製代碼

咱們看代碼發現其實都是PackageUpdatedTask這個執行方法,代碼比較多,咱們只貼重點部分,詳細的能夠去看源碼:

private class PackageUpdatedTask implements Runnable {

        ...

        public void run() {
            ...
            switch (mOp) {
                case OP_ADD: {
                    for (int i = 0; i < N; i++) {
                        ...
                        mIconCache.updateIconsForPkg(packages[i], mUser);
                        ...
                    }
                    ...
                    break;
                }
                case OP_UPDATE:
                    for (int i = 0; i < N; i++) {
                        ...
                        mIconCache.updateIconsForPkg(packages[i], mUser);
                        ...
                    }
                    break;
                case OP_REMOVE: {
                    ...
                    for (int i = 0; i < N; i++) {
                        ...
                        mIconCache.removeIconsForPkg(packages[i], mUser);
                    }
                }
                case OP_UNAVAILABLE:
                    for (int i = 0; i < N; i++) {
                        ...
                    }
                    break;
            }
            ...
            // Update shortcut infos
            if (mOp == OP_ADD || mOp == OP_UPDATE) {
                ...
                synchronized (sBgLock) {
                    for (ItemInfo info : sBgItemsIdMap) {
                        if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
                            ...
                            // Update shortcuts which use iconResource.
                            if ((si.iconResource != null)
                                    && packageSet.contains(si.iconResource.packageName)) {
                                Bitmap icon = Utilities.createIconBitmap(
                                        si.iconResource.packageName,
                                        si.iconResource.resourceName, context);
                                if (icon != null) {
                                    si.setIcon(icon);
                                    ...
                                }
                            }

                            ComponentName cn = si.getTargetComponent();
                            if (cn != null && packageSet.contains(cn.getPackageName())) {
                                ...
                                if (si.isPromise()) {
                                    ...
                                    si.updateIcon(mIconCache);
                                }

                                if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
                                        && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
                                    si.updateIcon(mIconCache);
                                    ...
                                }
                                ...
                            }
                            ...
                        } 
                    }
                }
            }
        }
    }複製代碼

在上面代碼中咱們看到OP_ADD(安裝)、OP_UPDATE(更新)時都是調用的mIconCache.removeIconsForPkg,而和OP_REMOVE(卸載)時調用mIconCache.removeIconsForPkg方法,而在下面又調用了si.setIcon(icon)、si.updateIcon來更新Icon,咱們分別來看看這四個方法,首先看第一個方法(removeIconsForPkg):

public synchronized void updateIconsForPkg(String packageName, UserHandleCompat user) {
        removeIconsForPkg(packageName, user);
        try {
            PackageInfo info = mPackageManager.getPackageInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            long userSerial = mUserManager.getSerialNumberForUser(user);
            for (LauncherActivityInfoCompat app : mLauncherApps.getActivityList(packageName, user)) {
                addIconToDBAndMemCache(app, info, userSerial);
            }
        } catch (NameNotFoundException e) {
            Log.d(TAG, "Package not found", e);
            return;
        }
    }複製代碼

首先調用removeIconsForPkg方法,也就是刪除Icon,看代碼:

public synchronized void removeIconsForPkg(String packageName, UserHandleCompat user) {
        removeFromMemCacheLocked(packageName, user);
        long userSerial = mUserManager.getSerialNumberForUser(user);
        mIconDb.getWritableDatabase().delete(IconDB.TABLE_NAME,
                IconDB.COLUMN_COMPONENT + " LIKE ? AND " + IconDB.COLUMN_USER + " = ?",
                new String[] {packageName + "/%", Long.toString(userSerial)});
    }複製代碼

首先調用removeFromMemCacheLocked方法,其實這個方法就是從mCache中把緩存的CacheEntry對象刪除,而後再從數據庫刪除Icon。而後回到updateIconsForPkg方法,接着調用addIconToDBAndMemCache方法,也就是添加Icon到數據庫:

@Thunk void addIconToDBAndMemCache(LauncherActivityInfoCompat app, PackageInfo info, long userSerial) {
        // Reuse the existing entry if it already exists in the DB. This ensures that we do not
        // create bitmap if it was already created during loader.
        ContentValues values = updateCacheAndGetContentValues(app, false);
        addIconToDB(values, app.getComponentName(), info, userSerial);
    }複製代碼

首先調用updateCacherAndGetContentValues這個方法:

@Thunk ContentValues updateCacheAndGetContentValues(LauncherActivityInfoCompat app, boolean replaceExisting) {
        final ComponentKey key = new ComponentKey(app.getComponentName(), app.getUser());
        CacheEntry entry = null;
        if (!replaceExisting) {
            entry = mCache.get(key);
            // We can't reuse the entry if the high-res icon is not present.
            if (entry == null || entry.isLowResIcon || entry.icon == null) {
                entry = null;
            }
        }
        if (entry == null) {
            entry = new CacheEntry();
            entry.icon = Utilities.createIconBitmap(app.getBadgedIcon(mIconDpi), mContext);
        }
        entry.title = app.getLabel();
        entry.contentDescription = mUserManager.getBadgedLabelForUser(entry.title, app.getUser());
        mCache.put(new ComponentKey(app.getComponentName(), app.getUser()), entry);

        return newContentValues(entry.icon, entry.title.toString(), mActivityBgColor);
    }複製代碼

這個方法是生成新的CacheEntry,以及Icon,放將其放置到mCache中緩存,就是咱們上面刪除的那個,而後經過調用newContentValues方法將Icon轉換成byte數組放到ContentValues中,最後存入數據庫中。這就是咱們安裝,更新,卸載時對於Icon的數據庫操做。咱們在Icon生成後其實要放到相應的應用對象中,以方便咱們顯示到桌面上,其實就是(setIcon(icon)、si.updateIcon(mIconCache))這兩個方法,第一個是直接將生成好的Icon放入到ShortcutInfo中,另外一個是從緩存獲取,咱們來看從緩存獲取這個方法:

public void updateIcon(IconCache iconCache) {
        updateIcon(iconCache, shouldUseLowResIcon());
    }複製代碼

調用updateIcon方法:

public void updateIcon(IconCache iconCache, boolean useLowRes) {
        if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
            iconCache.getTitleAndIcon(this, promisedIntent != null ? promisedIntent : intent, user,
                    useLowRes);
        }
    }複製代碼

咱們看到此時調用了iconCache.getTitleAndIcon方法,也就是又回到咱們以前將的獲取Icon的方法了。

整個Icon加載的流程基本就是這些,有些我沒有詳細講解,本身看看就行了,Icon會放到ShortcutInfo中,在綁定圖標的時候會讀取出來顯示到桌面上,流程就是這樣的,若是要作切換主題其實就是從這裏入手。

設置壁紙

原生桌面長按桌面空白處,會出現壁紙、widget和設置三個菜單,咱們點擊壁紙會進入壁紙選擇設置界面,也就是WallpaperPickerActivity,WallpaperPickerActivity繼承WallpaperCropActivity,因此有些操做可能分別在這兩個類中進行。

設置壁紙是從WallpaperCropActivity中的setWallpaper方法開始的:

protected void setWallpaper(Uri uri, final boolean finishActivityWhenDone) {
        int rotation = BitmapUtils.getRotationFromExif(getContext(), uri);
        BitmapCropTask cropTask = new BitmapCropTask(
                getContext(), uri, null, rotation, 0, 0, true, false, null);
        final Point bounds = cropTask.getImageBounds();
        Runnable onEndCrop = new Runnable() {
            public void run() {
                updateWallpaperDimensions(bounds.x, bounds.y);
                if (finishActivityWhenDone) {
                    setResult(Activity.RESULT_OK);
                    finish();
                }
            }
        };
        cropTask.setOnEndRunnable(onEndCrop);
        cropTask.setNoCrop(true);
        cropTask.execute();
    }複製代碼

其中BitmapCropTask是一個異步任務,也就是執行異步任務設置壁紙而後調用onEndCrop中的run方法結束改界面,返回桌面。異步任務執行順序是:onPreExecute-->doInBackground-->onPostExecute。咱們看代碼:

public class BitmapCropTask extends AsyncTask<Void, Void, Boolean> {

    // Helper to setup input stream
    private InputStream regenerateInputStream() {
        ...
    }

    public boolean cropBitmap() {
        ...
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        return cropBitmap();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        ...
    }
}複製代碼

首先初始化,而後執行doInBackground方法,其實這個方法中執行的是cropBitmap方法,代碼:

public boolean cropBitmap() {
        ...
        if (mSetWallpaper) {
            //獲取WallpaperManager對象
            wallpaperManager = WallpaperManager.getInstance(mContext.getApplicationContext());
        }

        if (mSetWallpaper && mNoCrop) {
            try {
                //不須要裁切的狀況下,直接經過URI獲取圖片流
                InputStream is = regenerateInputStream();
                if (is != null) {
                    //若是圖片存在,設置壁紙
                    wallpaperManager.setStream(is);
                    Utils.closeSilently(is);
                }
            } catch (IOException e) {
                Log.w(LOGTAG, "cannot write stream to wallpaper", e);
                failure = true;
            }
            return !failure;
        } else {// 若是須要裁切
            // Find crop bounds (scaled to original image size)
            ...

            //獲取圖片的大小範圍
            Point bounds = getImageBounds();
            //判斷是否須要旋轉
            if (mRotation > 0) {
                rotateMatrix.setRotate(mRotation);
                inverseRotateMatrix.setRotate(-mRotation);
                ...
            }

            mCropBounds.roundOut(roundedTrueCrop);
            //若是寬高小於0則視爲失敗
            if (roundedTrueCrop.width() <= 0 || roundedTrueCrop.height() <= 0) {
                ...
                return false;
            }

            // 根據寬高比來設置縮放倍數
            int scaleDownSampleSize = Math.max(1, Math.min(roundedTrueCrop.width() / mOutWidth,
                    roundedTrueCrop.height() / mOutHeight));
            ...
            try {
                //經過流讀取圖片
                is = regenerateInputStream();
                ...
                decoder = BitmapRegionDecoder.newInstance(is, false);
                Utils.closeSilently(is);
            } catch (IOException e) {
                ...
            } finally {
               ...
            }

            Bitmap crop = null;
            if (decoder != null) {
                // Do region decoding to get crop bitmap
                BitmapFactory.Options options = new BitmapFactory.Options();
                if (scaleDownSampleSize > 1) {
                    options.inSampleSize = scaleDownSampleSize;
                }
                // 獲取切割圖片
                crop = decoder.decodeRegion(roundedTrueCrop, options);
                decoder.recycle();
            }

            if (crop == null) {//獲取切割圖片失敗
                // BitmapRegionDecoder has failed, try to crop in-memory
                is = regenerateInputStream();
                Bitmap fullSize = null;
                if (is != null) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    if (scaleDownSampleSize > 1) {
                        options.inSampleSize = scaleDownSampleSize;
                    }
                    //獲取原始圖片
                    fullSize = BitmapFactory.decodeStream(is, null, options);
                    Utils.closeSilently(is);
                }
                if (fullSize != null) {
                    // 計算切割圖片的範圍
                    ...
                    //生成切割圖片
                    crop = Bitmap.createBitmap(fullSize, roundedTrueCrop.left,
                            roundedTrueCrop.top, roundedTrueCrop.width(),
                            roundedTrueCrop.height());
                }
            }

            ...

            if (mOutWidth > 0 && mOutHeight > 0 || mRotation > 0) {
                ...

                Matrix m = new Matrix();
                // 不須要旋轉
                if (mRotation == 0) {
                    m.setRectToRect(cropRect, returnRect, Matrix.ScaleToFit.FILL);
                } else {//旋轉
                    ...
                }

                //生成新的旋轉後的圖片
                Bitmap tmp = Bitmap.createBitmap((int) returnRect.width(),
                        (int) returnRect.height(), Bitmap.Config.ARGB_8888);
                if (tmp != null) {
                    Canvas c = new Canvas(tmp);
                    Paint p = new Paint();
                    p.setFilterBitmap(true);
                    c.drawBitmap(crop, m, p);
                    crop = tmp;
                }
            }

            if (mSaveCroppedBitmap) {
                mCroppedBitmap = crop;
            }

            // Compress to byte array
            ByteArrayOutputStream tmpOut = new ByteArrayOutputStream(2048);
            //壓縮圖片成數組
            if (crop.compress(CompressFormat.JPEG, DEFAULT_COMPRESS_QUALITY, tmpOut)) {
                // If we need to set to the wallpaper, set it
                if (mSetWallpaper && wallpaperManager != null) {
                    try {
                        byte[] outByteArray = tmpOut.toByteArray();
                        //設置壁紙
                        wallpaperManager.setStream(new ByteArrayInputStream(outByteArray));
                        if (mOnBitmapCroppedHandler != null) {
                            mOnBitmapCroppedHandler.onBitmapCropped(outByteArray);
                        }
                    } catch (IOException e) {
                        ...
                    }
                }
            } else {
                ...
            }
        }
        return !failure; // True if any of the operations failed複製代碼

整個過程看上面代碼,解釋都卸載註釋裏面了,一些裁切計算問題看看代碼就知道了,最終就是轉換成流的形式進行設置壁紙。

最後

Github地址:github.com/yuchuangu85…

同步發佈:www.codemx.cn/2017/05/19/…

Android開發羣:192508518

微信公衆帳號:Code-MX

注:本文原創,轉載請註明出處,多謝。

相關文章
相關標籤/搜索