在我的應用程序有RecyclerView
與噸it.Images圖像加載爲用戶滾動RecyclerView與此代碼:安卓:java.util.concurrent.ThreadPoolExecutor中
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,url);
else
loader.execute(url);
不幸的是,有時,當用戶滾動這個快錯誤發生:
Task [email protected] rejected from
[email protected][Running, pool size = 9,
active threads = 9, queued tasks = 128, completed tasks = 279]
有沒有辦法檢測poolExecutor是否已滿並跳過圖像加載?
整個圖像類:
public class Image extends ImageView {
private AsyncTask<String,Integer,Bitmap> loader;
public Image(Context context) {
super(context);
this.setScaleType(ScaleType.FIT_XY);
}
public Image(Context context, AttributeSet attrs) {
super(context, attrs);
this.setScaleType(ScaleType.FIT_XY);
}
public void loadURL(String url) {
if(loader!=null)
loader.cancel(true);
loader=new AsyncTask<String, Integer, Bitmap>() {
@Override
protected Bitmap doInBackground(String... params) {
URL url = null;
byte[] bytes = null;
HttpURLConnection connection=null;
try {
url = new URL(params[0]);
connection=(HttpURLConnection) url.openConnection();
connection.setRequestProperty("Connection", "close");
connection.setRequestMethod("GET");
connection.setUseCaches(true);
InputStream is = null;
is=connection.getInputStream();
bytes = IOUtils.toByteArray(is);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (connection!=null)
connection.disconnect();
Bitmap res=null;
if(!isCancelled() && bytes!=null)
res=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
return res;
}
@Override
protected void onPostExecute(Bitmap res) {
if(res!=null) {
setImageBitmap(res);
_animate();
}
}
};
if (this.getDrawable()!=null) {
Bitmap bmp=((BitmapDrawable) this.getDrawable()).getBitmap();
this.setAnimation(null);
if (bmp!=null) {
bmp.recycle();
//Log.d("image","recycled");
}
this.setImageBitmap(null);
}
/*
ThreadPoolExecutor e =(ThreadPoolExecutor) Executors.newFixedThreadPool(9);
Log.d("pool size",e.getActiveCount()+"/"+e.getMaximumPoolSize());
if (e.getActiveCount() == e.getMaximumPoolSize()) {
}
*/
//start loading
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
else
loader.execute(url);
}
private void _animate() {
ValueAnimator bgAnim= ValueAnimator.ofObject(new IntEvaluator(),0,255);
bgAnim.setDuration(500);
bgAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
Image.this.getDrawable().setAlpha((int) (animation.getAnimatedValue()));
}
});
bgAnim.start();
}
}
可能重複的[android應用程序崩潰時超過線程池9和排隊的任務128](https://stackoverflow.com/questions/34395004/android-app-crashes-when-超線程池9和排隊任務128) –
而不是創建一個新的異步任務上傳創建一個圖像,只需創建一個並上傳所有圖像。 –
它引發單個AsyncTask。 java.lang.IllegalStateException:無法執行任務:任務已在運行。 – undefined