Why are some ContextCompat.getExternalFilesDirs inaccessible?

ContextCompat.getExternalFilesDirs (context, null) says:

Returns the absolute paths to directories of specific applications on all external storage devices, where the application can host permanent files that it owns.

For example, Huawei Honor running Android 5.1.1 returns the following from this method:

/storage/emulated/0/Android/data/my.package.name/files
/storage/sdcard1/Android/data/my.package.name/files

The second directory is a removable SD card. However, if I try to read or write to this directory, I get an exception:android.system.ErrnoException: open failed: EACCES (Permission denied)

The application has one WRITE_EXTERNAL_STORAGE. And it works great on Samsung Galaxy Note 4 running Android 4.4.4. This is not related to the additional permissions of Android 6.0, as this is the problem shown in 5.1.1.

The API says the application can place persistent files it owns, but it doesn't seem to be that way.

, Samsung. OEM- -, Android- ?

, .

File removable = ContextCompat.getExternalFilesDirs(context, null)[1];
if (removable.exists() && removable.canRead() && removable.canWrite()) {
    File test = new File(removable, "test");
    test.createNewFile(); // Throws the exception mentioned above
}

, mkdir .

+4
2

, :

package com.commonsware.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    File removable = ContextCompat.getExternalFilesDirs(this, null)[1];
    if (removable.exists() && removable.canRead() && removable.canWrite()) {
      File test = new File(removable, "test");
      try {
        test.createNewFile(); // Throws the exception mentioned above
      }
      catch (IOException e) {
        Log.e(getClass().getSimpleName(), "Exception creating file", e);
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
      }
    }
  }
}

Huawei Honor 5X, Android 6.0.1:

$ adb shell ls -al /storage/1A30-3598/Android/data/com.commonsware.myapplication/files
-rwxrwx--x u0_a29   sdcard_rw        0 2017-05-03 18:02 test

, , .

+1

, @CommonsWare ArrayIndexOutOfBoundsException: length = 1; index = 1 [0] [0]. , . - ,  

        File removable = ContextCompat.getExternalFilesDirs(this,null)[0];
    if (removable.exists() && removable.canRead() && removable.canWrite()) {

        THE_PATH = String.valueOf(removable);
        THE_PATH = THE_PATH + "/Documents/";

    }else {
        Toast.makeText(getApplicationContext(),"NO SD CARD", 
    Toast.LENGTH_LONG).show();

    }
0

Source: https://habr.com/ru/post/1676294/


All Articles