通过授予权限,保存文件显示“权限被拒绝”

时间:2018-10-18 05:17:44

标签: android android-permissions

我正在将图像从滑行保存到设备。我要求在首次运行App时获得许可,因为这就是我的应用程序所做的事情。

 final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DesiJewellery/");
public void saveImage(Bitmap bitmap, String img_title) {

    fname = img_title;
    myDir.mkdirs();
    File image = new File(myDir, fname);


    FileOutputStream outStream;
    if (image.exists()) {
        image.delete();
    }
    try {
        outStream = new FileOutputStream(image);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
        outStream.flush();
        outStream.close();
        success = true;
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

    if (success) {
        Toast.makeText(getActivity(), "Design saved - " + img_title, Toast.LENGTH_SHORT).show();
    } else {
       // Toast.makeText(getActivity(), "Something went wrong.", Toast.LENGTH_LONG).show();
    }
    // this one to show in gallery:

}

在仿真器中工作正常,但在实际设备中显示

java.io.FileNotFoundException:/storage/emulated/0/DesiJewellery/m_aad14.jpg(权限被拒绝)

权限检查。我在MainActivity上运行它。

public void isStoragePermissionGranted() {

    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED && checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {

        } else {
            requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        }
    } else {

    }
}  

P.S。-我有2个Real设备。它可以在Mashmallow和Nougat Emulator中使用,但问题仅在Oreo中使用。

2 个答案:

答案 0 :(得分:1)

您应该在Android Mainifest中添加 WRITE_EXTERNAL_PERMISSION ,如下所示:

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

答案 1 :(得分:1)

您可以尝试以下操作:

AsyncTask fileTask = new AsyncTask() {
    @Override
    protected Object doInBackground(Object[] objects) {
File directory = new File(Environment.getExternalStorageDirectory() + File.separator + "MyApplication");
if (!directory.exists()) {
                directory.mkdirs();
            }
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String name = " "+n+".jpg";
File pictureFile = new File(directory, name);
pictureFile.createNewFile();
try {
FileOutputStream out = new FileOutputStream(pictureFile);
   finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
   out.close();
} catch (Exception e) {
   e.printStackTrace();
}
return null;
 }
};
fileTask.execute();

请参考help