我想用Picasso库下载并保存多个图像,但我没有找到如何保存外部存储...(SD)
Picasso picasso = Picasso.with(context)
.load(url)
.into();
有可能吗?
答案 0 :(得分:0)
据我所知,这是不可能的。 Picasso只在单独的线程中异步缓存和下载图像。
我建议使用Piccaso进行缓存和显示图片,并使用异步任务将图像下载并保存到外部存储。
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("Starting download");
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
String root = Environment.getExternalStorageDirectory().toString();
System.out.println("Downloading");
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(root+"/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* After completing background task
* **/
@Override
protected void onPostExecute(String file_url) {
System.out.println("Downloaded");
}
}
您只需使用
调用上述类 new DownloadFileFromURL().execute(<The url you want to download from>);
您还需要向Manifest文件添加以下权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
希望有所帮助