活不多說(shuō) 上代碼:
Observable.create(new ObservableOnSubscribe<File>() {
@Override
public void subscribe(ObservableEmitter<File> e) throws Exception {
//通過(guò)gilde下載得到file文件,這里需要注意android.permission.INTERNET權(quán)限
e.onNext(Glide.with(mContext)
.load(imagePathList.get(currentViewPosition).getPath())
.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get());
e.onComplete();
}
}).subscribeOn(Schedulers.io())
.observeOn(Schedulers.newThread())
.subscribe(new Consumer<File>() {
@Override
public void accept(File file) throws Exception {
//獲取到下載得到的圖片侣姆,進(jìn)行本地保存
File pictureFolder = Environment.getExternalStorageDirectory();
//第二個(gè)參數(shù)為你想要保存的目錄名稱
File appDir = new File(pictureFolder, "your_picture_save_path");
if (!appDir.exists()) {
appDir.mkdirs();
}
String fileName = System.currentTimeMillis() + ".jpg";
File destFile = new File(appDir, fileName);
//把gilde下載得到圖片復(fù)制到定義好的目錄中去
copy(file, destFile);
// 最后通知圖庫(kù)更新
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(new File(destFile.getPath()))));
}
});
帶個(gè)復(fù)制文件的代碼:
/**
* 復(fù)制文件
*
* @param source 輸入文件
* @param target 輸出文件
*/
public void copy(File source, File target) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(source);
fileOutputStream = new FileOutputStream(target);
byte[] buffer = new byte[1024];
while (fileInputStream.read(buffer) > 0) {
fileOutputStream.write(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意要加權(quán)限:
最后需要注意的下載保存需要讀寫權(quán)限砰苍,6.0以后需手動(dòng)申請(qǐng)權(quán)限
android.permission.WRITE_EXTERNAL_STORAGE
android.permission.READ_EXTERNAL_STORAGE