在vendor/mediatek/proprietary/packages/apps/FileManager/src/com/mediatek/filemanager/FileInfoAdapter.java中导入如下类import java.util.Map;
import android.os.Handler;
import java.util.HashMap;
import android.os.Message;
import android.util.LruCache;在该类中添加全局变量private LruCache<String,Bitmap> mMemoryCache;
private int myThreadCount=0;在构造方法中对全局变量进行初始化int maxMemory=(int)(Runtime.getRuntime().maxMemory()/1024);//获取系统最大内存的方法,以KB为单位
int cacheSize=maxMemory/8;//规定占用内存的1/8
mMemoryCache=new LruCache<String,Bitmap>(cacheSize){
protect int sizeOf(String key,Bitmap bitmap){
return bitmap.getByteCount()/1024;//返回每个bitmap的内存大小,以kb为单位
}
};添加向mMemoryCache添加和获取bitmap的方法public void addBitmapToMemoryCache(String key,Bitmap bitmap){
if(getBitmapFromMemCache(key)==null){
mMemoryCache.put(key,bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key){
return mMemoryCache.get(key);
}获取位图资源icon=getBitmapFromMemCache(fileInfo.getFileAbsolutePath());//从LruCache中根据文件路径获取相应的位图
if(icon==null){
if(fileInfo.isDirectory()){
icon=BitmapFactory.decodeResource(mResources,R.drawable.fm_folder);
}else{
icon=BitmapFactory.decodeResource(mResources,R.drawable.fm_image);
}
if(myThreadCount<=10){
loadImage(mResource,fileInfo,mServiece,viewDirection);//如果线程数小于10个(太多会导致内存溢出),则调用loadImage方法将该位图加入LruCache中
}
}在主线程中定义一个Handler对象,用于更新UI操作final Handler mHandler=new Handler(){
@Override
public void handMessage(Message msg){
switch(msg.what){
case 0:
notifyDataSetChanged();//更新UI的操作
myThreadCount--;//UI更新完成以后就可以释放一个线程数,当然线程的释放并不是这里,而是在下面的thread=null
break;
default:
break;
}
}
};loadImage方法private void loadImage(Resources res,final FileInfo myFileInfo,FileManagerService service,final int viewDirection){
myThreadCount++;
Thread thread=new Thread(){
@Override
public void run(){
Bitmap icon=IconManager.getInstance().getIcon(mResources,myFileInfo,mService,viewDirection);//这里是获取缩略图的方法,是最耗时的部分,因此放在其他线程里处理,而不放在主线程中,但UI更新是线程不安全的,只能在主线程中进行
addBitmapToMemoryCache(myFileInfo.getFileAbsolutePath(),icon);
mHandler.sendEmptyMessage(0);//发送消息到主线程,让主线程更新UI
}
};
thread.start();//启动线程
thread=null;//释放线程以上功能已经实现,还可以用AsyncTask实现异步处理机制class ThumbnailAsynctask extends AsyncTask<Void,Void,Void>{
private FileInfo myFileInfo;
private int viewDirection;
public ThumbnailAsynctask(final FileInfo myFileInfo,final int viewDirection){
this.myFileInfo=myFileInfo;
this.viewDirection=viewDirection;
}
protected Void doInBackground(Void... params){
Bitmap icon=IconManger.getInstance().getIcon(mResources,myFileInfo,mService,viewDirection);
addBitmapToMemoryCache(myFileInfo.getFileAbsolutePath(),icon);
return null;
}
}调用定义的异步处理机制对象new ThumbnailAsynctask(fileInfo,viewDirection).execute();
转载请注明原文地址: https://ju.6miu.com/read-680412.html