即使具有用户权限也无法将文件保存在外部存储中[Android] [英] Can't save files on External Storage, even with user permissions [Android]

查看:84
本文介绍了即使具有用户权限也无法将文件保存在外部存储中[Android]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个用于在Android上进行图像处理的应用程序,但是我一直在编写用于保存图像的代码.

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

这是我使用的方法:

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);
                }
            });

}

每次执行此操作时,FileOutputStream都会给出FileNotFoundException.

Every time I execute this, FileOutputStream gives a FileNotFoundException.

我的清单:

<?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>

我正在Linux上使用内置的虚拟Nexus 5和Android 6.0在Android Studio 1.5.1上进行开发.

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

感谢您的帮助.

推荐答案

我在Android 6上遇到了相同的问题.这是由于新的权限模型所致.

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);
      }
    }
  }

这篇关于即使具有用户权限也无法将文件保存在外部存储中[Android]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆