最近有个需求需要下载封面图片保存到本地,并且同步到相册中。
利用Glide、Rxjava封装下以便复用。
//保存网络图片到相册
public static void saveImageUrlToGallery(Context context, String url,OnListener listener) {
Observable.just(url).map(new Func1<String, File>() {
@Override
public File call(String s) {
File file = null;
try {
file = Glide.with(context).load(s).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<File>() {
@Override
public void call(File file) {
if (file != null) {
saveImageToGallery(context,file.getAbsolutePath());
listener.onSuccess(null);
}else {
listener.onFail();
}
}
});
}
//保存图片到相册
public static void saveImageToGallery(Context context, String path) {
File file = new File(path);
//其次把文件插入到系统图库
try {
String filename = path.substring(path.lastIndexOf('/') + 1);
MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), filename, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 通知图库更新
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
MediaScannerConnection.scanFile(context, new String[]{file.getAbsolutePath()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(uri);
context.sendBroadcast(mediaScanIntent);
}
});
} else {
String relationDir = file.getParent();
File file1 = new File(relationDir);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(file1.getAbsoluteFile())));
}
}