在terminal连上手机
adb shell dumpsys meminfo pagename(自己程序的包名)
发现自己的程序占用的内存很大,而且在 输入信息的最下面有个 Asset Allocations
他下面展示了 很多这种信息 而且有很多重复的
zip:/data/app//base.apk:/assets/fonts/FZHTJW.TTF: 3116K
zip:/data/app/.apk:/assets/fonts/FZKTJW.TTF: 3836K
于是我就想 这个是不是会造成内存泄漏,上网一搜 果然
typeface =Typeface.createFromAsset(mAssetManager, "fonts/FZKTJW.TTF"); 这种方式创建的typeface不会被回收,重复创建就会造成内存泄漏。
解决办法:
在app初始化的时候创建一次,然后整个app直接引用他,这样内存就不会再增加了
也可以创建一个类来管理
public class FontManager {
private static FontManager FONT_MANAGER;
private AssetManager mAssetManager;
private static final Map<String, Typeface> CACHE_FONT_MAP = new HashMap<String, Typeface>();
private FontManager(Application application) {
mAssetManager = application.getAssets();
}
public static void createInstance(Application application) {
if (FONT_MANAGER == null) {
synchronized (FontManager.class) {
if (FONT_MANAGER == null) {
FONT_MANAGER = new FontManager(application);
}
}
}
}
public static FontManager getInstance() {
if (FONT_MANAGER == null) {
// FONT_MANAGER = new FontManager((Application) App.getContext());
// synchronized (FontManager.class) {
//
// }
throw new NullPointerException("NullPoint Exception, Please call createInstance FONT_MANAGER!");
}
return FONT_MANAGER;
}
public Typeface getFont(FontType type) {
if (type == null) {
return null;
}
final String key = type.getValue();
Typeface typeface = null;
switch (type) {
case FZFSJW:
if (CACHE_FONT_MAP.containsKey(key)) {
return CACHE_FONT_MAP.get(key);
} else {
typeface = Typeface.createFromAsset(mAssetManager, "fonts/FZFSJW.TTF");
CACHE_FONT_MAP.put(key, typeface);
}
break;
case FZKTJW:
if (CACHE_FONT_MAP.containsKey(key)) {
return CACHE_FONT_MAP.get(key);
} else {
typeface = Typeface.createFromAsset(mAssetManager, "fonts/FZKTJW.TTF");
CACHE_FONT_MAP.put(key, typeface);
}
break;
case FZHTJW:
if (CACHE_FONT_MAP.containsKey(key)) {
return CACHE_FONT_MAP.get(key);
} else {
typeface = Typeface.createFromAsset(mAssetManager, "fonts/FZHTJW.TTF");
CACHE_FONT_MAP.put(key, typeface);
}
break;
case FZSSJW:
if (CACHE_FONT_MAP.containsKey(key)) {
return CACHE_FONT_MAP.get(key);
} else {
typeface = Typeface.createFromAsset(mAssetManager, "fonts/FZSSJW.TTF");
CACHE_FONT_MAP.put(key, typeface);
}
break;
default:
break;
}
return typeface;
}
public enum FontType {
FZFSJW("FZFSJW"),
FZKTJW("FZKTJW"),
FZHTJW("FZHTJW"),
FZSSJW("FZSSJW"),
// FZFSJW("FZFSJW");
String value;
FontType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
// -----------------------------------------------------------------------
// Convenient
// -----------------------------------------------------------------------
public static class FLFont {
public static Typeface getFont(FontType type) {
try {
FontManager manager = FontManager.getInstance();
return manager.getFont(type);
} catch (NullPointerException e) {
e.printStackTrace();
}
return null;
}
}