我在doInBackground()
的{{1}}方法中获取了图片的缩略图。如果我使用AsyncTask
取消AsyncTask
,则运行AsyncTask
时会遇到问题。我在logcat中遇到一个奇怪的异常。该应用程序未终止,但logcat显示异常消息。
我的doInBackground()如下所示
cancel()
getImageThumbnail方法
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
String path = params[0];
bitmap = getImageThumbnail(MainActivity.this,path);
//Some cache mechanism
return bitmap;
}
如果异步任务处于runnign状态,如果我调用 public static Bitmap getImageThumbnail(Context context,String path) {
ContentResolver cr = context.getContentResolver();
Cursor ca = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.MediaColumns._ID}, MediaStore.MediaColumns.DATA + "=?", new String[]{path}, null);
if (ca != null && ca.moveToFirst()) {
int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
ca.close();
//At this line I am getting exception
Bitmap thumbnail = MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
return thumbnail;
}
return ((BitmapDrawable) context.getResources().getDrawable(R.drawable.dummy)).getBitmap();
}
我在logcat中收到以下消息
asyncTask.cancel(true)
如何避免该异常??
答案 0 :(得分:0)
在创建位图缩略图之前,您正在关闭光标,将getImageThumbnail
方法更改为如下所示:
public static Bitmap getImageThumbnail(Context context,String path) {
ContentResolver cr = context.getContentResolver();
Cursor ca = null;
ca = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.MediaColumns._ID}, MediaStore.MediaColumns.DATA + "=?", new String[]{path}, null);
if (ca != null && ca.moveToFirst()) {
int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
//At this line I am getting exception
Bitmap thumbnail = MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
ca.close();
return thumbnail;
}
return ((BitmapDrawable) context.getResources().getDrawable(R.drawable.dummy)).getBitmap();
}
答案 1 :(得分:0)
使用asyncTask.cancel(false)
取消异步任务。然后,在isCancelled()
中致电getImageThumbnail()
之前,请先检查doInBackground()
。
您的doInBackground()
现在将成为:
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
String path = params[0];
if(!isCancelled()) {
bitmap = getImageThumbnail(MainActivity.this,path);
//Some cache mechanism
}
return bitmap;
}
在isCancelled()
中执行任何操作之前,您还应该先检查postExecute()
。