大家早上好,
我有一个从互联网下载图片的异步任务。我有三个带有名称的按钮,如果按下与已经下载的名称不同的名称,我希望它取消任务并使用新名称启动一个。
DownloadImageTask downloadPicTask = null;
int tasksRunning;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.detail, container, false);
fillData();
return rootView;
}
public void fillData(){
if(downloadPicTask != null){
Log.i(TAG,"Trying to cancel task...");
downloadPicTask.cancel(true);
}else{
Log.i(TAG,"why why why");
}
...
downloadPicTask = new DownloadImageTask(imageView);
downloadPicTask.execute(firstName,lastName);
tasksRunning = tasksRunning + 1;
Log.i(tag,String.valueOf(tasksRunning));
...
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
boolean canceled = false;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
@Override
protected void onCancelled() {
Log.i(TAG, "Async Cancelled");
canceled = true;
}
protected Bitmap doInBackground(String... params) {
... //downloading the bitmap here
}
protected void onPostExecute(Bitmap result) {
if(!canceled){
bmImage.setImageBitmap(result);
}
}
}
出于某种原因,一旦第一个任务开始并且我按了不同的名称,downloadPicTask 将返回 null,因此它不会取消。这只发生在第一次取消尝试! 即使任务返回 null,它也可以正常运行,并在完成时设置 imageview。后续尝试取消任务都成功,因为第一次 downloadPicTask 后不再返回 null。
有人对此有想法吗?