我在AsyncTask
的doInBackground()
方法中獲取圖像的縮略圖。如果我使用cancel()
取消AsyncTask
,則運行AsyncTask
時出現問題。我在logcat中遇到了一個奇怪的異常。該應用程序沒有終止,但logcat顯示異常消息。在AsyncTask中獲取圖像縮略圖的例外
我doInBackground()是象下面
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
String path = params[0];
bitmap = getImageThumbnail(MainActivity.this,path);
//Some cache mechanism
return bitmap;
}
getImageThumbnail方法
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();
}
雖然異步任務是runnign狀態,如果我叫asyncTask.cancel(true)
我收到以下消息in logcat
06-11 17:49:45.380 1600-1708/com.sample.appl V/MiniThumbFile﹕ Got exception checking file magic:
java.nio.channels.ClosedChannelException
at java.nio.FileChannelImpl.checkOpen(FileChannelImpl.java:73)
at java.nio.FileChannelImpl.lock(FileChannelImpl.java:161)
at android.media.MiniThumbFile.getMagic(MiniThumbFile.java:161)
at android.provider.MediaStore$InternalThumbnails.getThumbnail(MediaStore.java:635)
at android.provider.MediaStore$Images$Thumbnails.getThumbnail(MediaStore.java:1008)
at com.appsforbb.common.filesystem.ImageUtils.getImageThumbnail(ImageUtils.java:55)
at com.appsforbb.basic.filemanager.CacheImageView$BitmapWorkerTask.doInBackground(CacheImageView.java:79)
at com.appsforbb.basic.filemanager.CacheImageView$BitmapWorkerTask.doInBackground(CacheImageView.java:58)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
如何避免這種異常?
你爲什麼要做'ca.close();'兩次? –
@MurtazaKhursheedHussain我刪除ca.close但仍然得到相同的結果! – Chandrakanth