这边主题实现,主要是替换背景,以及应用的ICON,及应用图标的背景。
/*
* 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 mCache = new HashMap(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> 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
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 mThemesNames = new ArrayList();
// private List mThemesBitmaps = null;
private Map mMapImgs = new HashMap();
private com.android.launcher3.themeAdapter.ImageAdapter mImageAdapter;
public static boolean sdCardExist;
GridView gridview;
int mCounter;
ArrayList namepkg = new ArrayList();;
@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 {
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;
}
}
//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);
}
}
}