在我的界面中,用户从可变数量的歌曲中进行选择,当选择一首歌曲时,我需要显示相关的背景图像。 用户需要在加载图像时保持对界面的控制,并且仍然能够更改歌曲。
我目前执行此操作的方式是使用 AsyncTask。
我正在使用以下方法执行它:
if (LoadBG!=null&&!LoadBG.isCancelled())
LoadBG.cancel(false);
LoadBG = new loadBG();
LoadBG.execute((Object) diff.BGPath);
如果上一个任务仍在运行,则尝试取消该任务并重新创建它。
任务代码执行位图加载:
protected Boolean doInBackground(Object... param) {
String pathName = param[0].toString();
if (!pathName.equals(gfxStore.currentBGPath)) {
currentBGLoaded = false;
while(overlayOpacity!=255)
Thread.yield();
//set current bg
if (this.isCancelled())
return true;
Bitmap d;
try
{
d = gfxStore.factory.decodeFile(pathName,gfxStore.opts);
}
catch (OutOfMemoryError e)
{
System.gc();
return true;
}
if (this.isCancelled())
{
d.recycle();
d = null;
System.gc();
return true;
}
Bitmap s;
try
{
s = gfxStore.scaleImageForCanvas(canvasWidth, canvasHeight,d );
}
catch (OutOfMemoryError e)
{
//XXX uuuugh
System.gc();
return true;
}
if (this.isCancelled())
{
d.recycle();
d=null;
s.recycle();
s=null;
System.gc();
return true;
}
d.recycle();
d=null;
System.gc();
gfxStore.currentBG = s;
gfxStore.currentBGPath = pathName;
wasChange = true;
}
else
wasChange=false;
return true;
}
我已经做了相当困惑的回收、清空、运行GC,所有这些都试图取消当前任务,以便新创建的任务有足够的内存可用于分配,但无论我尝试什么,我总是会遇到内存不足异常当尝试运行太多太快时(大约 4/5 次)
图像是1024x768 jpg文件,并要求1.5mb内存分配,我使用bitmapfactory选项:
opts.inPreferredConfig = Bitmap.Config.RGB_565;
opts.inPurgeable = true;
opts.inSampleSize = 1;
绝对-任何-建议将不胜感激,我已经搜索了无数关于回收位图、清空、GCing、尝试使用可清除位图的信息。
最佳答案
您能否尝试使用互斥体序列化调用,以便仅执行一个操作(即使由于某种原因被取消)?请参阅下面的非常基本的方法。显然,您可以在 doInBackground 方法中进行更多选择性锁定,但您明白了。
static class DecodeLock extends Object {
}
static public DecodeLock lockObject = new DecodeLock();
// ...
protected Boolean doInBackground(Object... param) {
synchronized (lockObject) {
String pathName = param[0].toString();
if (!pathName.equals(gfxStore.currentBGPath)) {
//[..snip]
}
}
关于android - 如何取消运行 BitmapFactory.decodeFile() 的 AsyncTask 并进行清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5732702/