Launcher3主题实现

这边主题实现,主要是替换背景,以及应用的ICON,及应用图标的背景。

修改源码IconCache.java文件

/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.launcher3;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

/**
 * Cache of application icons. Icons can be made from any thread.
 */
public class IconCache {
    @SuppressWarnings("unused")
    private static final String TAG = "IconCache";

    private static final int INITIAL_ICON_CACHE_CAPACITY = 50;
    private String SDPath = "/storage/sdcard1/theme/";
    private String SDPhonePath = "mnt/sdcard/theme/";
    public static  boolean  sdCardExist;

    private static class CacheEntry {
        public Bitmap icon;
        public String title;
    }

    private final Bitmap mDefaultIcon;
    private final Context mContext;
    private final PackageManager mPackageManager;
    private final HashMap<ComponentName, CacheEntry> mCache = new HashMap<ComponentName, CacheEntry>(INITIAL_ICON_CACHE_CAPACITY);
    private int mIconDpi;

    SharedPreferences mSharedPrefs;

    public IconCache(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        mContext = context;
        // ybf
        mSharedPrefs = context.getSharedPreferences(LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
        mPackageManager = context.getPackageManager();
        mIconDpi = activityManager.getLauncherLargeIconDensity();

        // need to set mIconDpi before getting default icon
        mDefaultIcon = makeDefaultIcon();

    }

    public Drawable getFullResDefaultActivityIcon() {
        return getFullResIcon(Resources.getSystem(), android.R.drawable.sym_def_app_icon);
    }

    @SuppressWarnings("deprecation")
    public Drawable getFullResIcon(Resources resources, int iconId) {
        Drawable d;
        try {
            d = resources.getDrawableForDensity(iconId, mIconDpi);
            //Bitmap b = addThemeLogo(((BitmapDrawable) d).getBitmap());// ybf
            //d = new FastBitmapDrawable(b);// ybf
        } catch (Resources.NotFoundException e) {
            d = null;
        }

        return (d != null) ? d : getFullResDefaultActivityIcon();
    }

    // ybf
    public Drawable getFullResIcon(String packageName, int iconId) {
        // add 
        String themeKeyname = mSharedPrefs.getString("theme_key", "default");
        // android.os.SystemProperties.get("persist.sys.theme.key", "default");
        if (!themeKeyname.equals("default")) {
            String iconpath = SDPath + themeKeyname + "/" + themeKeyname + "_" + convertToIconResName(packageName) + ".png";
            if (new File(iconpath).exists()) {
                return new FastBitmapDrawable(BitmapFactory.decodeFile(iconpath));
            }

        }
        // add by 
        return getFullResDefaultActivityIcon();// ybf

    }

    /*
     * public Drawable getFullResIcon(String packageName, int iconId) { Resources resources; try { resources =
     * mPackageManager.getResourcesForApplication(packageName); } catch (PackageManager.NameNotFoundException e) {
     * resources = null; } if (resources != null) { if (iconId != 0) { return getFullResIcon(resources, iconId); } }
     * return getFullResDefaultActivityIcon(); }
     */

    public Drawable getFullResIcon(ResolveInfo info) {
        return getFullResIcon(info.activityInfo);
    }

    // ybf
//   public Drawable getFullResIcon(ActivityInfo info) {
//   // add by xuxin
//   String themeKeyname = mSharedPrefs.getString("theme_key", "default");//
//  // android.os.SystemProperties.get("persist.sys.theme.key",
//   // "default");
//   String iconpath;
//   if (!themeKeyname.equals("default")) {
//   iconpath = SDPath + themeKeyname + "/" + themeKeyname + "_" + convertToIconResName(info.name) + ".png";
//   if (new File(iconpath).exists()) {
//   return new FastBitmapDrawable(BitmapFactory.decodeFile(iconpath));
//   } else {
//   iconpath = SDPath + themeKeyname + "/" + themeKeyname + "_" + convertToIconResName(info.packageName) + ".png";
//   if (new File(iconpath).exists()) {
//   return new FastBitmapDrawable(BitmapFactory.decodeFile(iconpath));
//   }
//   }
//   }
//   // add by xuxin
//   return getFullResDefaultActivityIcon();//
//  
//   }

    /**
    * 获取原始应用icon
     */
    public Drawable getFullResIcon(ActivityInfo info) {

        Resources resources;
        try {
            resources = mPackageManager.getResourcesForApplication(info.applicationInfo);
        } catch (PackageManager.NameNotFoundException e) {
            resources = null;
        }
        if (resources != null) {
            int iconId = info.getIconResource();
            if (iconId != 0) {
                return getFullResIcon(resources, iconId);
            }
        }
        return getFullResDefaultActivityIcon();
    }
    /**
     *创建默认图标
     */
    private Bitmap makeDefaultIcon() {
        Drawable d = getFullResDefaultActivityIcon();
        Bitmap b = Bitmap.createBitmap(Math.max(d.getIntrinsicWidth(), 1), Math.max(d.getIntrinsicHeight(), 1),
                Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        d.setBounds(0, 0, b.getWidth(), b.getHeight());
        d.draw(c);
        c.setBitmap(null);
        return b;
    }

    /**
     * Remove any records for the supplied ComponentName.
     * 删除任何纪录ComponentName提供。
     */
    public void remove(ComponentName componentName) {
        synchronized (mCache) {
            mCache.remove(componentName);
        }
    }

    /**
     * Empty out the cache.
     * 清空缓存
     */
    public void flush() {
        synchronized (mCache) {
            mCache.clear();
        }
    }

    /**
     * Empty out the cache that aren't of the correct grid size
     * 清空缓存不正确的网格尺寸
     */
    public void flushInvalidIcons(DeviceProfile grid) {
        synchronized (mCache) {
            Iterator<Entry<ComponentName, CacheEntry>> it = mCache.entrySet().iterator();
            while (it.hasNext()) {
                final CacheEntry e = it.next().getValue();
                if (e.icon.getWidth() != grid.iconSizePx || e.icon.getHeight() != grid.iconSizePx) {
                    it.remove();
                }
            }
        }
    }

    /**
     * Fill in "application" with the icon and label for "info."
     */
    public void getTitleAndIcon(AppInfo application, ResolveInfo info, HashMap<Object, CharSequence> labelCache) {
        synchronized (mCache) {
            CacheEntry entry = cacheLocked(application.componentName, info, labelCache);

            application.title = entry.title;
            application.iconBitmap = entry.icon;
        }
    }

    public Bitmap getIcon(Intent intent) {
        synchronized (mCache) {
            final ResolveInfo resolveInfo = mPackageManager.resolveActivity(intent, 0);
            ComponentName component = intent.getComponent();

            if (resolveInfo == null || component == null) {
                Log.e(TAG, "--> resolveInfo == null || component == null");
                return mDefaultIcon;
            }

            CacheEntry entry = cacheLocked(component, resolveInfo, null);
            Log.e(TAG, "--> entry" + entry.icon);
            return entry.icon;
        }
    }

    public Bitmap getIcon(ComponentName component, ResolveInfo resolveInfo, HashMap<Object, CharSequence> labelCache) {
        synchronized (mCache) {
            if (resolveInfo == null || component == null) {
                return null;
            }

            CacheEntry entry = cacheLocked(component, resolveInfo, labelCache);
            return entry.icon;
        }
    }

    public boolean isDefaultIcon(Bitmap icon) {
        return mDefaultIcon == icon;
    }

//  private CacheEntry cacheLocked(ComponentName componentName, ResolveInfo info, HashMap<Object, CharSequence> labelCache) {
//      CacheEntry entry = mCache.get(componentName);
//      if (entry == null) {
//          entry = new CacheEntry();
//
//          mCache.put(componentName, entry);
//
//          ComponentName key = LauncherModel.getComponentNameFromResolveInfo(info);
//          if (labelCache != null && labelCache.containsKey(key)) {
//              entry.title = labelCache.get(key).toString();
//          } else {
//              entry.title = info.loadLabel(mPackageManager).toString();
//              if (labelCache != null) {
//                  labelCache.put(key, entry.title);
//              }
//          }
//          if (entry.title == null) {
//              entry.title = info.activityInfo.name;
//          }
//
//          entry.icon = Utilities.createIconBitmap(getFullResIcon(info), mContext);
//      }
//      return entry;
//  }

    // ybf
    private CacheEntry cacheLocked(ComponentName componentName, ResolveInfo info, HashMap<Object, CharSequence> labelCache) {
        sdCardExist = Environment.getExternalStorageState()  
                .equals(android.os.Environment.MEDIA_MOUNTED);
        CacheEntry entry = mCache.get(componentName);
        // add by xuxin
        if (entry == null) {
            entry = new CacheEntry();
        }
        mCache.put(componentName, entry); 
        ComponentName key = LauncherModel.getComponentNameFromResolveInfo(info);
        if (labelCache != null && labelCache.containsKey(key)) {
            entry.title = labelCache.get(key).toString();
        } else {
            entry.title = info.loadLabel(mPackageManager).toString();
            if (labelCache != null) {
                labelCache.put(key, entry.title);
            }
        }
        if (entry.title == null) {
            entry.title = info.activityInfo.name;
        }
        String themeKeyname;
        if(sdCardExist){
             themeKeyname = mSharedPrefs.getString("theme_key", "default");//////////////////////////////////////////////////////////////
        }else{
             themeKeyname = "default";/////////////////////////////////////////////////////////////////
        }
        //String themeKeyname = mSharedPrefs.getString("theme_key", "default");//
        Log.e(TAG, "get key --- " + themeKeyname);
        Log.e(TAG, "sd --- " + sdCardExist);
        String iconpath;
        if (!themeKeyname.equals("default")) {
            iconpath = SDPath + themeKeyname + "/" + themeKeyname + "_" + convertToIconResName(info.activityInfo.name) + ".png";
            Log.e(TAG, "应用图标名字---iconpath-1->" + iconpath);
            if (new File(iconpath).exists()) {
                entry.icon = BitmapFactory.decodeFile(iconpath);
                Log.e(TAG, "entry.icon-2->" + entry.icon);
            } else {
                iconpath = SDPath + themeKeyname + "/" + themeKeyname + "_" + convertToIconResName(info.activityInfo.packageName)
                        + ".png";
                Log.e(TAG, "iconpath-3->" + entry.icon);
                if (new File(iconpath).exists()) {
                    entry.icon = BitmapFactory.decodeFile(iconpath);
                    Log.e(TAG, "entry.icon-4->" + entry.icon);
                } else {
                    entry.icon = Utilities.createIconBitmap(getFullResIcon(info), mContext);
                    Log.e(TAG, "entry.icon-5->" + entry.icon);
                }
            }
        } else {
            Log.e(TAG, "entry.icon-6--使用默认---->" + entry.icon);
            entry.icon = Utilities.createIconBitmap(getFullResIcon(info), mContext);

        }
        // add by xuxin
        return entry;// ybf

    }

    private String convertToIconResName(String input) {
        Log.e(TAG, "convertToIconResName-->"+input.replace('.', '_').toLowerCase() );//返回包名
        return input != null && !input.equals("") ? input.replace('.', '_').toLowerCase() : input;
    }
    //创建的图片会盖在icon上面,所以在Utilities里面设置背景Icon
    private Bitmap addThemeLogo(Bitmap srcBitmap) {
        String themeKeyname = mSharedPrefs.getString("theme_key", "default");
        // android.os.SystemProperties.get("persist.sys.theme.key", "default");

        Bitmap b2 = BitmapFactory.decodeFile(SDPath + themeKeyname + "/" + themeKeyname + "_icon_bg.png");
        if (themeKeyname.equals("default") || b2 == null) {
            Log.e(TAG, "return srcBitmap");
            return srcBitmap;
        }
        Bitmap b3 = Bitmap.createBitmap(srcBitmap.getWidth() + 20, srcBitmap.getHeight() + 20, srcBitmap.getConfig());
        Canvas canvas = new Canvas(b3);
        canvas.drawBitmap(srcBitmap, 0, 0, new Paint(Paint.FILTER_BITMAP_FLAG));
        canvas.drawBitmap(b2, 0, Math.abs(srcBitmap.getHeight() - b2.getHeight()), new Paint(Paint.FILTER_BITMAP_FLAG));
        Log.e(TAG, "return b3");
        return b3;
    }

    public HashMap<ComponentName, Bitmap> getAllIcons() {
        synchronized (mCache) {
            HashMap<ComponentName, Bitmap> set = new HashMap<ComponentName, Bitmap>();
            for (ComponentName cn : mCache.keySet()) {
                final CacheEntry e = mCache.get(cn);
                set.put(cn, e.icon);
            }
            return set;
        }
    }
}

桌面在添加一个Activity主题入口

package com.android.launcher3;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.android.launcher3.themeAdapter.ImageAdapter;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;
public class ThemeActivity extends Activity {
    private String TAG = "ThemeActivity";
    private SharedPreferences sp;
    private String SDpath = "/storage/sdcard1/theme/";
    String path = "/storage/sdcard1/theme_thumbs";
    private List<String> mThemesNames = new ArrayList<String>();
    // private List<Bitmap> mThemesBitmaps = null;
    private Map<String, Bitmap> mMapImgs = new HashMap<String, Bitmap>();
    private com.android.launcher3.themeAdapter.ImageAdapter mImageAdapter;
    public static boolean sdCardExist;
    GridView gridview;
    int mCounter;
    ArrayList<String> namepkg  = new ArrayList<String>();;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.theme_picker);
        sp = getSharedPreferences(LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
        AsyncLoadedImage mAsyncLoadedImage = new AsyncLoadedImage();
        mAsyncLoadedImage.execute();


        mImageAdapter = new ImageAdapter(this, mThemesNames, mMapImgs);
        gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(mImageAdapter);




    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Log.e(TAG, "sdCardExist is "+sdCardExist);
        sdCardExist = Environment.getExternalStorageState()  
                .equals(android.os.Environment.MEDIA_MOUNTED);
        //if(sdCardExist){
            gridview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    Log.e("SDpath", "mThemesNames.get(position)-- " + namepkg.get(position) + "");
                    Log.e("SDpath", "-position- " + position+ "");
                    boolean fileEffect = isFileEffect(SDpath + namepkg.get(position));

                    Log.e("SDpath", "fileEffect---->" + fileEffect);
                    Log.e("SDpath", "file---->" + new File(SDpath + namepkg.get(position)));
                    Log.e("SDpath", "namepkg.size() -- -----------------" + namepkg.size());
                    WallpaperManager wallpaperManager = WallpaperManager.getInstance(ThemeActivity.this);
                    Log.e(TAG, "position*****"+position+"---------namepkg.size()"+namepkg.size());
                    if (position  == namepkg.size()) {

                        sp.edit().putString("theme_key", "default").commit();
                        try {
                            wallpaperManager.setResource(android.content.res.Resources.getSystem().getIdentifier(
                                    "default_wallpaper", "drawable", "android"));
                            Log.e(TAG, "1");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Log.e(TAG, "2");
                        // 杀掉当前进程
                        android.os.Process.killProcess(android.os.Process.myPid());
                        Log.e(TAG, "3");
                    } else if (isFileEffect(SDpath + namepkg.get(position ))) {

                        sp.edit().putString("theme_key", namepkg.get(position)).commit();

                        try {
                            wallpaperManager.setBitmap(BitmapFactory.decodeFile(SDpath + namepkg.get(position )
                                    + "/" + namepkg.get(position ) + "_wallpaper.jpg"));
                            Log.e(TAG, "4");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Log.e(TAG, "5");
                        //Toast.makeText(getApplicationContext(), "设置成功", 0).show();
                        android.os.Process.killProcess(android.os.Process.myPid());
                    } else {
                        // down load this theme
                    }

                }

            });
    //}  //if end 


    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
    Handler mAsyncHandler = new Handler() {
        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                mImageAdapter.refreshDatas();
            }
        }
    };
    class AsyncLoadedImage extends AsyncTask<Object, Bitmap, Object> {

        private void loadLogos(String root) {
            File rootDir = new File(root);
            if (rootDir.exists()) {
                File[] files = rootDir.listFiles();


                int flagIdx = 0;
                for (int i = 0; i < files.length; i++) {
                    if (files[i].isFile()) {
                        String path = files[i].getPath();
                        Bitmap cover = getBitmap(path);
                        if (cover != null) {
                            String name_key = path;
                            mMapImgs.put(path, getBitmap(path));
                            mThemesNames.add(path);
                            String[] split = name_key.split("/");
                            String string = split[split.length-1];
                            Log.e(TAG, "----------------"+string);
                            String[] name = string.split("\\.");
                            String packagename = name[0];
                            Log.e(TAG, "-------packagename--------"+name[0]);
                            namepkg.add(packagename);
                        }
                        flagIdx++;
                        // Refresh
                        if (mThemesNames.size() % 3 == 0 || flagIdx == (files.length - 1)) {
                            Message mMessage = mAsyncHandler.obtainMessage();
                            mMessage.what = 1;
                            mAsyncHandler.sendMessage(mMessage);
                        }
                    }
                }


            }
        }
        @Override
        protected Object doInBackground(Object... params) {
            Log.i("Async", "fileArray new success");
            if( "".equals(path)){
                return null;
            }else{
                loadLogos(path);
            }

            return null;
        }
        @Override
        public void onProgressUpdate(Bitmap... value) {
            Log.e("Async", "onProgressUpdate:wxp addImage");
        }
        @Override
        protected void onPostExecute(Object result) {
        }
    }
    private Bitmap getBitmap(String path) {
        Bitmap cover = null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
            cover = ThumbnailUtils.extractThumbnail(bitmap, 450, 300);
            bitmap.recycle();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cover;
    }
    private String trimExtension(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int i = filename.lastIndexOf('.');
            if ((i > -1) && (i < (filename.length()))) {
                return filename.substring(0, i);
            }
        }
        return null;
    }
    private boolean isFileEffect(String name) {
        File file = new File(name);
        Log.e(TAG, " file.exists()--->" + file.exists() + "");
        Log.e(TAG, "file.isDirectory()--->" + file.isDirectory() + "");
        if (file.exists() && file.isDirectory() /* &&(file.list().length > 0) */)
            return true;
        else
            return false;
    }

}

3 修改Utilities 文件

 //ybf  更换icon背景图片
    public static Bitmap createFramedPhoto2(int left,int top,Context context){
         String path="/storage/sdcard1/theme/";
     Paint backgroundPaint = new Paint();
        Canvas canvas = sCanvas;
       Rect dst = new Rect(left-30,top-30,left+120,top+120);
       SharedPreferences mSharedPrefs = context.getSharedPreferences(LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
       String themeKeyname = mSharedPrefs.getString("theme_key", "default");
       Bitmap b2;
       if(themeKeyname.equals("default")){
           b2 = BitmapFactory.decodeResource(context.getResources(),R.drawable.iconbackground);
           canvas.drawBitmap(b2, null, dst,backgroundPaint);
           Log.e(TAG, "default-1-icon");
       }else if(!IconCache.sdCardExist){

           b2 = BitmapFactory.decodeResource(context.getResources(),R.drawable.iconbackground);
           canvas.drawBitmap(b2, null, dst,backgroundPaint);
           Log.e(TAG, "default-2-icon");
       }else{
           b2 = BitmapFactory.decodeFile(path + themeKeyname + "/" + themeKeyname + "_icon_bg.png");
           canvas.drawBitmap(b2, null, dst,backgroundPaint);
           Log.e(TAG, "theme-3-icon");   
       }

      // Bitmap bitmapss = BitmapFactory.decodeResource(context.getResources(),id);

    return b2;
   }
    /**
     * Returns a Bitmap representing the thumbnail of the specified Bitmap.
     *
     * @param bitmap The bitmap to get a thumbnail of.
     * @param context The application's context.
     *
     * @return A thumbnail for the specified bitmap or the bitmap itself if the
     *         thumbnail could not be created.
     */
    static Bitmap resampleIconBitmap(Bitmap bitmap, Context context) {
        synchronized (sCanvas) { // we share the statics :-(
            if (sIconWidth == -1) {
                initStatics(context);
            }
            if (bitmap.getWidth() == sIconWidth && bitmap.getHeight() == sIconHeight) {
                return bitmap;
            } else {
                final Resources resources = context.getResources();
                return createIconBitmap(new BitmapDrawable(resources, bitmap), context);
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_38148680/article/details/80946243