gpt4 book ai didi

android - 保存图像时 java.io.FileNotFoundException 权限被拒绝

转载 作者:行者123 更新时间:2023-11-29 14:30:06 25 4
gpt4 key购买 nike

private void saveImage(Bitmap bitmap){
try {
String path = Environment.getExternalStorageDirectory().toString();
Toast.makeText(getActivity(), path, Toast.LENGTH_SHORT).show();
OutputStream fOut = null;
File file = new File(path, mWallpaper.getId().toString() + ".jpg");
fOut = new FileOutputStream(file);

bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
fOut.flush();
fOut.close();

MediaStore.Images.Media.insertImage(getActivity().getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (MalformedURLException e) {
Toast.makeText(getActivity(), "Error saving wallpaper. MAL", Toast.LENGTH_SHORT).show();
} catch (IOException e1) {
Toast.makeText(getActivity(), "Error saving wallpaper.", Toast.LENGTH_SHORT).show();
e1.printStackTrace();
}
}

我将其添加到我的 AndroidManifests 中:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

我正在尝试将图像保存到/storage/emulated/0/。

编辑

int permissionCheck = ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {

if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

} else {

ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
permissionCheck);
}
}

我已将此添加到我的 fragment 的 onCreate(),但我仍然不是请求。

最佳答案

if (Build.VERSION.SDK_INT >= 23) {
int permissionCheck = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}

如果您使用 >=api 23,请执行此操作。在此之后添加您的代码。使用此代码,您可以向用户请求运行时许可。

Requesting Permissions at Run Time Documentation from official Android site

关于android - 保存图像时 java.io.FileNotFoundException 权限被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43519311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com