第一种 AndroidManifest.xml application节点添加
android:requestLegacyExternalStorage="true"
android:name=".app.MyApplication"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_security_config"
android:roundIcon="@mipmap/ic_launcher"
tools:replace="android:allowBackup"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:requestLegacyExternalStorage="true"//targetSdkVersion >28都需
第二种,推荐使用
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), drawableId);
String displayName = System.currentTimeMillis() + "jpg";
String mimeType = "image/jpeg";
Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.JPEG;
DownLoadPictureUtil.addBitmapToAlbum(this,bitmap,displayName,mimeType,compressFormat);
/**
* api >= 29时调用 保存图片到系统相册
* @param bitmap
* @param displayName
* @param mimeType
* @param compressFormat
*/
public static void addBitmapToAlbum(Context context,Bitmap bitmap,String displayName , String mimeType , Bitmap.CompressFormat compressFormat){
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName);
values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
} else {
values.put(MediaStore.MediaColumns.DATA, Environment.getExternalStorageDirectory().getPath()+Environment.DIRECTORY_DCIM+displayName);
}
ContentResolver contentResolver = context.getContentResolver();
Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
ToastUtils.show( "保存成功 ");
if (uri != null) {
OutputStream outputStream = null;
try {
outputStream = contentResolver.openOutputStream(uri);
bitmap.compress(compressFormat, 100, outputStream);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (outputStream != null) {
}
}
}