简体   繁体   English

Android-拒绝创建新文件的权限

[英]Android - Permission Denied for creating new file

Im trying to create a file in Android, and even after following all the other answers im still getting permission denied. 我试图在Android中创建一个文件,甚至在遵循所有其他答案之后,我仍然无法获得许可。 Error happens in saveImage() method. saveImage()方法中发生错误。

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

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState)
        verifyStoragePermissions(this);
    }

  //HERE IS THE METHOD THAT ASKS FOR PERMISSIONS
    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) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

  @Override //ON REQUEST PERMISSION RESULT, 
//I ACCEPTED THE PERMISSION, THE CODE HERE WAS EXECUTED AS IT SHOULD
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {

            case 1: {
                Log.d(TAG,"THIS IS FOR THE WRITE/READ PERMISSIONS");
                Log.d(TAG,grantResults.toString());
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG,"[Persmission accepted for writing/reading]");


                    // permission was granted, yay! Do the
                    // camera related task you need to do.
                } else {
                    Log.d(TAG,"[Permission denied]");
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }

            }

            // other 'case' lines to check for other
            // permissions this app might request.
        }
    }

 //THE METHOD WHERE THE ERROR HAPPENS
 public String saveImage(Bitmap myBitmap) {

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

        File wallpaperDirectory = new File(
                Environment.getExternalStorageDirectory() + "TEST_APP_PHOTO_FOLDER");

        // have the object build the directory structure, if needed.
        if (!wallpaperDirectory.exists()) {

            wallpaperDirectory.mkdirs();
        }

        try {

            File f = new File(wallpaperDirectory + "testfile.jpg");

            f.mkdirs();
          f.createNewFile(); // <--- STACK TRACE POINTS HERE

            FileOutputStream fo = new FileOutputStream(f);
..
..
..

The error happens in the saveImage() method. 该错误发生在saveImage()方法中。 I have comments explaining where it happens. 我有评论解释发生的地方。 I have tried the method with the f.mkdirs() and without it, does not work either way. 我已经尝试过使用f.mkdirs()的方法,但是如果没有它,则将无法正常工作。 Permission denied both times. 权限两次均被拒绝。

STACK TRACE 堆栈跟踪

java.io.IOException: Permission denied
        at java.io.UnixFileSystem.createFileExclusively0(Native Method)
        at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:281)
        at java.io.File.createNewFile(File.java:1000)
        at car.andrej.tradingapp.ProfileActivity.ProfileActivity.saveImage(ProfileActivity.java:263)
        at car.andrej.tradingapp.ProfileActivity.ProfileActivity.onActivityResult(ProfileActivity.java:220)
        at android.app.Activity.dispatchActivityResult(Activity.java:7556)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4487)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4534)
        at android.app.ActivityThread.-wrap20(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1752)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6944)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

In the manifest : 在清单中:

 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

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

What am i missing?... 我想念什么?...

This isn't an Android permissions issue. 这不是Android权限问题。 Rather, the Exception is due to Linux permissions, though inadvertently. 相反,该Exception是由于Linux权限造成的,尽管是无意间造成的。

In instantiating the File s used in saveImage() , you're concatenating the name of the new file/directory to Environment.getExternalStorageDirectory() ; 在实例化saveImage()使用的File ,您要将新文件/目录的名称连接到Environment.getExternalStorageDirectory() ; eg, for wallpaperDirectory : 例如,对于wallpaperDirectory

new File(Environment.getExternalStorageDirectory() + "TEST_APP_PHOTO_FOLDER")

This is implicitly calling toString() on Environment.getExternalStorageDirectory() and directly appending the name to it without the necessary path separator in between, so you end up with a full name that's something like /storage/emulated/0TEST_APP_PHOTO_FOLDER . 这是在Environment.getExternalStorageDirectory() toString()上隐式调用toString()并直接在其后附加名称,而无需使用必需的路径分隔符,因此最终得到的全名类似于/storage/emulated/0TEST_APP_PHOTO_FOLDER This refers to a file in the parent of the external storage directory, and you don't have write access there, thus the Exception . 这是指外部存储目录的父目录中的文件,并且您在那里没有写访问权,因此就是Exception

Simply change your File instantiations to use the constructor that takes separate File and String arguments; 只需更改您的File实例以使用带有单独FileString参数的构造函数; the first for the parent directory, and the second for the name. 第一个用于父目录,第二个用于名称。 Basically, change the plus sign to a comma. 基本上,将加号更改为逗号。 For example: 例如:

new File(Environment.getExternalStorageDirectory(), "TEST_APP_PHOTO_FOLDER")

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

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