我正在从服务器加载几个图像并写入应用程序的内存。
我是这样的:
在一个循环中,我运行一个获取图像并将其写入文件的方法。
将第一个文件写入内存后,下一个文件应该开始加载。所以我们循环到列表的末尾。
循环结束后,我启动了一个已经在手机上处理文件的方法。
但是,出现了一个问题——即使在循环结束时,流仍然是开放的FileOutputStream。并且在启动第二种方法的时候,并不是所有的流都被关闭了,也就是说,并不是所有的图片都被记录在了手机上。结果,第二种方法无法使用所有图片。
我做了第一种方法synchronized——我只实现了加载顺序,但这并不影响流。
问题是如何跟踪所有文件下载和记录的时刻。
因为我这样写文件:
FileOutputStream ostream = new FileOutputStream(targetImgFile);
首先想到的是跟踪方法的运行ostream.close()。我知道在它运行之后 - 所有文件都被记录下来。但我找不到信息如何跟踪它是否有效?或者任何人都可以提出任何替代方案?
====
UPD:
这是用于从服务器加载图像的类:
public class LoaderQR {
private Context mContext;
private String sourceImgPath; //address image on server
private File targetImgFile; //
public LoaderQR(Context context, String pathImg, File imgFile) {
mContext = context;
sourceImgPath = pathImg;
targetImgFile = imgFile;
}
synchronized public void downloadImg() {
Target target = new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
try {
FileOutputStream ostream = new FileOutputStream(targetImgFile);
if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream)) {
ostream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
Picasso.with(mContext).load(sourceImgPath).into(target);
}
}
=====
UPD-2:
相同的代码,但在“老派”版本中:
public class LoaderQR {
private static final String TAG = "Download Task";
private Context mContext;
private String sourceImgPath; //address image on server
private File targetImgFile; //
public LoaderQR(Context context, String pathImg, File imgFile) {
mContext = context;
sourceImgPath = pathImg;
targetImgFile = imgFile;
}
synchronized public void downloadImgOld() {
try {
URL url = new URL(sourceImgPath);//Create Download URl
HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
c.connect();//connect the URL Connection
//If Connection response is not OK then show Logs
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
FileOutputStream fos = new FileOutputStream(targetImgFile);//Get OutputStream for NewFile Location
InputStream is = c.getInputStream();//Get InputStream for connection
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);//Write new file
}
//Close all connection after doing task
fos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
targetImgFile = null;
}
}
}
问题是一样的 - 并非所有文件都有时间添加。
告诉我如何更好地检查所有文件是否已添加到手机内存中并且可以进一步使用它们?
对于“老派”,您可以申请
AsyncTask。我们给它一个列表,它会循环加载所有文件并在最后调用回调:我们用:
问题并不完全清楚,但是流的过度关闭是惊人的,使用如下代码: