简体   繁体   English

使用Android创建文件时,即使获得了权限,也会出现“拒绝权限”错误

[英]Getting a Permission denied error when creating a file with Android, even when permission is given

I have this in my manifest: 我的清单中有这个:

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

This is where I am trying to create and write to a file (it is in a file called EnterUserInfo.java : 这是我尝试创建和写入文件的位置(该文件位于名为EnterUserInfo.java的文件中:

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};


/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        System.out.println("INSIDEEEEEE");
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    } else {
        System.out.println("HEREEEEEEEEE");
    }
}

private void writeToFile(String data, Context context) {

    verifyStoragePermissions(this);
    String FILENAME = "new_clients.txt";
    String string = "hello world!";

    try {
        FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
        fos.write(string.getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


    try {
        FileOutputStream fos = context.openFileOutput("new_clients.txt", Context.MODE_PRIVATE);
        fos.write(data.getBytes());
        fos.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

When I try to create a file, this is what appears: 当我尝试创建文件时,将显示以下内容:

I/System.out: HEREEEEEEEEE
W/ContextImpl: Failed to ensure /data/user/0/c.b.project/files: mkdir failed: EACCES (Permission denied)
W/FileUtils: Failed to chmod(/data/user/0/cs.b07.cscb07courseproject/files): android.system.ErrnoException: chmod failed: EACCES (Permission denied)
W/System.err: java.io.FileNotFoundException: /data/user/0/c.b.project/files/new_clients.txt (Permission denied)
W/System.err:     at java.io.FileOutputStream.open(Native Method)
W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
W/System.err:     at android.app.ContextImpl.openFileOutput(ContextImpl.java:506)
W/System.err:     at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:192)
W/System.err:     at EnterUserInfo.writeToFile(EnterUserInfo.java:69)

As you can see, it prints here meaning the permission is granted, but right after it gives a Permission Denied error. 如您所见,它将here打印here表示已授予该权限,但在它发出Permission Denied错误之后。 Any idea how to solve this? 任何想法如何解决这个问题?

Edit: On a side note, when it says that it tries to save to /data/user/0/cs.b07.cscb07courseproject/files , is that within the project or is that saved on my computer? 编辑:在旁注中,当它说它尝试保存到/data/user/0/cs.b07.cscb07courseproject/files ,是在项目内还是保存在我的计算机上? Because when I go to my terminal and do cd /data/ or cd /data neither is found. 因为当我去终端并执行cd /data/cd /data都找不到。

Edit: writeToFile() is called in the same class and file posted above, and this is the code (the function below is called when a user hits the "register" button in the UI: 编辑:在上面发布的相同类和文件中调用writeToFile() ,这是代码(当用户在UI中单击“注册”按钮时,将调用以下函数:

public void createNewUser(View view) {
    // a data string is created here:
    // String data = "asd";
    writeToFile(data, this);
}

Edit 2: Please note that I did ask for permission at runtime in my verifyStoragePermissions() method. 编辑2:请注意,我确实在运行时通过verifyStoragePermissions()方法请求权限。 Unless something is wrong with that way of asking for permission (which I don't think it is because a prompt does appear which asks the user for permission), then I think the issue is with something else. 除非请求许可的方式有问题(我不认为这是因为确实出现提示询问用户许可的提示),否则我认为问题出在其他方面。

You do not need any permissions to call openFileOutput() . 您不需要任何权限即可调用openFileOutput() This writes a file to the private application-specific data area, which is owned by your application. 这会将文件写入您的应用程序拥有的专用于专用应用程序的数据区域。

Judging by these errors: 从以下错误判断:

W/ContextImpl: Failed to ensure /data/user/0/c.b.project/files: mkdir failed: EACCES (Permission denied)
W/FileUtils: Failed to chmod(/data/user/0/cs.b07.cscb07courseproject/files): android.system.ErrnoException: chmod failed: EACCES (Permission denied)

It looks like someone has changed the file ownership (or access rights) on your application's private data directory /data/user/0/cbproject/ . 似乎有人更改了应用程序专用数据目录/data/user/0/cbproject/上的文件所有权(或访问权限)。 This directory should be owned by your application's user ID and therefore your application should have the necessary rights to write to it. 该目录应归您的应用程序的用户ID所有,因此您的应用程序应具有写入该目录的必要权限。

Uninstall your app (which should delete that directory) and then reinstall your app (which should recreate the directory with the correct permissions). 卸载您的应用程序(应该删除该目录),然后重新安装您的应用程序(应该使用正确的权限重新创建目录)。

Requesting Permissions at Run Time 在运行时请求权限

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. 从Android 6.0(API级别23)开始,用户在应用程序运行时(而不是在安装应用程序时)授予应用程序权限。 This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app. 这种方法简化了应用程序的安装过程,因为用户在安装或更新应用程序时无需授予权限。

More about runtime permission 有关运行时权限的更多信息
Refer Answer 参考答案

Hi firstly you have to check which android SDK version you are using 嗨,首先,您必须检查您使用的是哪个Android SDK版本

if it is less than 23 than you just have to put your permission in manifest file it work 如果它小于23,而您只需要在清单文件中放入许可,它就会起作用

if android version greater than 23 you should put all permission in manifest file as well as you should ask user permission for run time ( only first attempt ) 如果android版本大于23,您应该将所有权限放入清单文件中,并且您应该向用户询问运行时的权限 (仅首次尝试)
for this you should follow this link https://stackoverflow.com/a/33162451/4741746 为此,您应该点击此链接https://stackoverflow.com/a/33162451/4741746

One more thing you can don is to change compileSdkVersion and buildToolsVersion to below 23 like 22 (but i will not suggest you for this because new features above 23 you can not be use ) 您可以做的另一件事是将compileSdkVersion和buildToolsVersion更改为23以下,例如22(但我不建议您这样做,因为23以上的新功能您将无法使用)

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

   defaultConfig {
      minSdkVersion 16
      targetSdkVersion 23
   }
} 

if not working let me know 如果不工作,请告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM