Can't save files on External Storage, even with user permissions [Android]

丶灬走出姿态 提交于 2019-12-22 08:17:46

问题


I'm developing an app for images manipulation on Android, but I'm stuck in writing the code for image saving.

Here's the method I use:

private void saveImageToExternalStorage(Bitmap finalBitmap) {
    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-" + n + ".jpg";
    File file = new File(myDir, fname);
    if (file.exists())
        file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }


    // Tell the media scanner about the new file so that it is
    // immediately available to the user.
    MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });

}

Every time I execute this, FileOutputStream gives a FileNotFoundException.

My manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gabrielerestuccia.testimmagini">

<application
    ...
</application>

<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

</manifest>

I'm developing this on Android Studio 1.5.1 on Linux, using the built-in virtual Nexus 5 with Android 6.0.

Thanks for the help.


回答1:


I had the same problem on Android 6. This is because of new permission model.

You can check dynamically if you have permission with following piece of code:

private static boolean canWriteToExternalStorage(Context context) {
    return ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}

You can also enable writing permission for your app by going to Settings -> Apps -> Your App -> App Permissions and switch on Storage item.

In order to ask your user for this permission you should add in your Activity this piece of code:

public void onCreate(Bundle savedInstanceState) {
    ...
    checkWritingPermission();
}

@Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == REQUEST_CODE_PERMISSION) {
      if (grantResults.length >= 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        // permission was granted
      } else {
        // permission wasn't granted
      }
    }
  }

  private void checkWritingPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        // permission wasn't granted
      } else {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION);
      }
    }
  }



回答2:


 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        _bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

        //you can create a new file name "test.jpg" in sdcard folder.
        File f = new File(Environment.getExternalStorageDirectory()
                                + File.separator + "test.jpg")
        f.createNewFile();
        //write the bytes in file
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());

        // remember close de FileOutput
        fo.close();


来源:https://stackoverflow.com/questions/35826015/cant-save-files-on-external-storage-even-with-user-permissions-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!