java.io.IOException:权限被拒绝,无法创建文件

New*_*bie 3 android

我按照本教程拍照并保存到设备存储中,但是执行该操作时出现异常

java.io.IOException: Permission denied 
 on line:

File image = File.createTempFile(imageFileName, ".jpg", storageDir);
Run Code Online (Sandbox Code Playgroud)

如何解决呢?

private File createImageFile() throws IOException
{
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "Camera");
    File image = File.createTempFile(imageFileName, ".jpg", storageDir);

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}
Run Code Online (Sandbox Code Playgroud)

-编辑-
这是我的清单

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.idea.takephoto">

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>
Run Code Online (Sandbox Code Playgroud)

小智 9

如果您的目标 api 级别 >=29 或者您使用的是 android 10,请在应用程序标记的应用程序清单文件中添加以下行

android:requestLegacyExternalStorage="true"


ישו*_*ותך 5

Android文档中一样,您需要写入外部存储,必须在清单文件中请求WRITE_EXTERNAL_STORAGE权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   ...
</manifest>
Run Code Online (Sandbox Code Playgroud)

如果您使用API​​ 23(棉花糖)及更高版本,则需要在运行时请求权限,因为它是危险权限