添加权限
<!-- 允许程序写入外部存储,如SD卡上写文件-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 读取外置存储权限-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
application中 添加节点 android:requestLegacyExternalStorage="true" (targetSdkVersion >= 29 此节点不添加一直为null亲测 坑呀)
屏幕截图 或者 view截图均可
1.动态获取存储权限
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
int permission = ActivityCompat.checkSelfPermission(context,Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(CropDetailsActivity.this, PERMISSIONS_STORAGE,
REQUEST_PERMISSION_CODE);
}else {
//获取到权限进行图片保存
Bitmap bmp =convertViewToBitmap(mSharePopLayout);
saveImageToGallery(bmp);
}
}
(view可用当前页面布局id或者子view布局id)
public static BitmapconvertViewToBitmap(View view) {
view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
return bitmap;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode ==REQUEST_PERMISSION_CODE) {
getShareImg();
}else {
ToastUtils.show(context, "拒绝储存,前往设置打开读写权限");
}
}
private void saveImageToGallery(Bitmap bmp) {
// 首先保存图片
File appDir =new File(Environment.getExternalStorageDirectory(), "名称自拟");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName ="图片名称自拟";
File file =new File(appDir, fileName);
try {
FileOutputStream fos =new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(this.getContentResolver(),
file.getAbsolutePath(), fileName, null);
}catch (FileNotFoundException e) {
e.printStackTrace();
}
// 最后通知图库更新
ToastUtils.show(context, "保存成功");
}
网友评论