use of com.xxf.permission.PermissionDeniedException in project xxf_android by NBXXF.
the class SystemUtils method saveImageToAlbum.
/**
* 保存图片到相册
* 自动请求权限 没有权限报异常 {@link PermissionDeniedException}
*
* @param context
* @param picName 是name 不说full path
* @param bmp
* @return
*/
public static Observable<File> saveImageToAlbum(FragmentActivity context, String picName, Bitmap bmp) {
return XXF.requestPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE).compose(new RxPermissionTransformer(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)).flatMap(new Function<Boolean, ObservableSource<File>>() {
@Override
public ObservableSource<File> apply(Boolean aBoolean) throws Exception {
return Observable.fromCallable(new Callable<File>() {
@Override
public File call() throws Exception {
// 其次把文件插入到系统图库
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, picName);
values.put(MediaStore.MediaColumns.MIME_TYPE, com.xxf.utils.FileUtils.getMimeType(picName));
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
ContentResolver contentResolver = context.getContentResolver();
Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (uri == null) {
throw new RuntimeException("图片保存失败");
}
OutputStream fos = contentResolver.openOutputStream(uri);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
return new File(UriUtils.getPath(applicationContext, uri));
} else {
File appDir = applicationContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (!appDir.exists()) {
appDir.mkdir();
}
// 文件的名称设置为 系统时间.jpg
File file = new File(appDir, picName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(context, new String[] { file.getAbsolutePath() }, new String[] { com.xxf.utils.FileUtils.getMimeType(file.getAbsolutePath()) }, new MediaScannerConnection.OnScanCompletedListener() {
@Override
public void onScanCompleted(String path, Uri uri) {
}
});
// 锤子8.1 必须下面这种扫描方式
MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), picName, null);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
return file;
}
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
});
}
Aggregations