[英]How to check if context can still be used in android?
在我的android應用中,我有一個異步任務,該任務下載一張圖片並將其保存到外部存儲中,然后重復執行直到下載完所有圖片為止。 這可能需要一段時間,並且我從調用它的活動中引用了上下文,每次下載的映像在異步中都引用了幾次。
在此過程中,用戶可能已按回去或結束了上下文。
如何檢查是否仍可以在異步任務中使用它?
這是我的異步任務代碼:
package async;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import common.Common;
import common.FishCategory;
import http.Network;
import interfaces.ImageDownloader;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
public class Async_getAllFishPics extends AsyncTask<FishCategory, Void, FishCategory> {
String link;
ImageDownloader callerContext;
List<FishCategory> categoryList;
public Async_getAllFishPics(ImageDownloader callerContext, List<FishCategory> categoryList) {
this.callerContext = callerContext;
this.categoryList = categoryList;
for (FishCategory fish : categoryList) {
link = fish.getLink();
if (!link.equals("")) {
String imgpath = Common.getImagePath(link);
File file = new File(android.os.Environment.getExternalStorageDirectory(), imgpath);
if (!file.exists() && Network.isNetworkAvailable((Context)callerContext)) {
execute(fish);
break;
}
}
}
}
@Override
protected FishCategory doInBackground(FishCategory... fishes) {
Bitmap bitmap = Network.DownloadImage((Context) callerContext, link);
try {
saveImage(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
return fishes[0];
}
@Override
protected void onPostExecute(FishCategory fish) {
try {
fish.setLink(link);
new Async_getAllFishPics(callerContext, categoryList);
} catch(Exception e) {
e.printStackTrace();
}
}
private void saveImage(Bitmap bitmap) throws IOException {
if (bitmap != null) {
String path = Environment.getExternalStorageDirectory().toString();
String imgpath = Common.getImagePath(link);
File file = new File(path, imgpath);
file.getParentFile().mkdirs();
String abs = file.getAbsolutePath();
OutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(((Activity)callerContext).getContentResolver(),abs,file.getName(),file.getName());
}
}
}
為什么不改用ApplicationContext? 至少在關閉應用程序之前,您將確保上下文將存在。
context.getApplicationContext()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.