在setOnClickListener中我将url传递给另一个类中的方法,从片段下载图像,但是在启动应用程序后,它不能正常工作(它显示Toast消息但图像没有下载)但是从第二次单击它是工作得很好。
这是我的代码:
downloadimg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String[] urls = new String[50];
for (int i = 0; i < images.size(); i++) {
urls[i] = images.get(i).getLarge();
}
DownloadImages downloadImages= new DownloadImages();
downloadImages.downloadImage(getActivity(),urls, images.get(0).getName());
Toast.makeText(getActivity(), "Download Completed", Toast.LENGTH_SHORT).show();
getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Log.i("TAG", "scanning File jbdv");
}
});
这是完整的DownloadImages类
public class DownloadImages extends AppCompatActivity {
public void downloadImage(final Context ctx, String[]imgloc, final String folder) {
for (int i = 0; i < imgloc.length; i++) {
Picasso.with(ctx)
.load(imgloc[i])
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/~" +folder);
if (!myDir.exists()) {
myDir.mkdirs();
}
String name = new Date().getTime() + ".jpg";
myDir = new File(myDir, name);
FileOutputStream out = new FileOutputStream(myDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Log.i("TAG", "scanning File " +myDir.getAbsolutePath());
} catch (Exception e) {
// some action
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
);
}
}
}
答案 0 :(得分:0)
将代码放在onStart()方法
中并且为了快速访问图像,请在后台进行