0

I want create new file and write/read app settings. isExternalStorageAvailable() return false and should true. Android emulator external memory = 200mb.

 boolean isExternalStorageAvailable() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
            return true;
        }
        return false;
    }

Added permissions to manifest file:

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

Code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
        saveButton.setEnabled(false);
        System.out.println("Available: "+isExternalStorageAvailable()+", ReadOnly: "+isExternalStorageReadOnly());
    }
    else {
        myExternalFile = new File(getExternalFilesDir(filepath), filename);
    }
}
Makyen
  • 31,849
  • 12
  • 86
  • 121
  • I tried https://www.journaldev.com/9400/android-external-storage-read-write-save-file without success –  Jan 08 '18 at 10:39
  • Keep in mind that I'm not familiar with Android, but is it possible that `isExternalStorageAvailable()` is returning false because it simply isn't there and *not* that the program doesn't have permissions to use it? My advice would be to verify the type of external storage returned by `Environment.getExternalStorageState()`. – Neil Jan 08 '18 at 10:40
  • Here you can see code + emulator + logcat: https://i.imgur.com/Gn5LlOn.png –  Jan 08 '18 at 10:54
  • 1
    Please don't make more work for people by vandalizing your posts. By posting on the Stack Exchange (SE) network, you've granted a non-revocable right, under the [CC BY-SA 3.0 license](//creativecommons.org/licenses/by-sa/3.0), for SE to distribute that content (i.e. regardless of your future choices). By SE policy, the non-vandalized version of the post is the one which is distributed. Thus, any vandalism will be reverted. – Makyen Jul 30 '18 at 18:01

2 Answers2

0

To get all external storage paths this can be used:

    File[] extSDCardPaths = null;
    try {
        extSDCardPaths = ContextCompat.getExternalFilesDirs(ctx, null);
    } catch (Exception e) {
        // handle
    }

    for (File f : extSDCardPaths) {
        if (Environment.isExternalStorageRemovable(f)) {
            // check if anything found
        }
    }

If extSDCardPaths returns something then ext storage is available.

The above works for > 4.4(KitKat) only

The below hack can be used as fallback for lower OS versions:

String[] fallback = {"/storage/sdcard1/", "/mnt/ext_card/", "/mnt/extSdCard/", "/storage/extsdcard/",
            "/mnt/extsdcard/", "/storage/extSdCard/", "/mnt/external_sd", "/storage/MicroSD/",
            "/storage/external_SD/", "/storage/ext_sd/", "/storage/removable/sdcard1/", "/mnt/sdcard/external_sd/",
            "/storage/ext_sd/", "/mnt/emmc/", "/data/sdext/", "/sdcard/sd/"};

   for (String path : fallback) {
        if (new File(path).exists()) {
                // found an ext. dir
            break;
        }
   }
Demonick
  • 2,116
  • 3
  • 30
  • 40
  • "Unable to create external files directory" https://i.imgur.com/5flOFsw.png –  Jan 08 '18 at 11:13
  • See edited answer, if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { // then do the fallback – Demonick Jan 08 '18 at 11:21
  • Ye i use SDK 15. Tested without success: https://i.imgur.com/Nu2GPLs.png –  Jan 08 '18 at 12:06
0

If your application is targeting and running on marshmallow or above, you must gain permission to read/write to external storage, you must request permission from user explicitly after declaring permission in manifest.

  1. Make sure you have this in your manifest: <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  2. Check for permission explicitly. If not provided, request it:

    public void checkPermissionReadStorage(Activity activity){
             if (ContextCompat.checkSelfPermission(activity,      
    Manifest.permission.READ_EXTERNAL_STORAGE) !=     
    PackageManager.PERMISSION_GRANTED) {
    
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
    
                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
    
            } else {
    
                // No explanation needed, we can request the permission.
    
                ActivityCompat.requestPermissions(activity,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_STORAGE);
    
                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
    }
    
  3. Receive permission response:

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PermissionManager.MY_PERMISSIONS_REQUEST_READ_STORAGE:
                //premission to read storage
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                    // Permission granted. Call your storage related code here
    
                } else {
    
                    // permission denied.
                    // Handle permission failed here.
                }
                return;
    
    
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
    

Code was taken from here

Vijai
  • 1,067
  • 2
  • 11
  • 25
  • I have SDK version 15 so should work without this code. But anyway i will test soon. –  Jan 08 '18 at 12:13
  • If you dont target api 23 or above, using the above approach is useless since the permissions are granted as soon as the application is installed. May be you are having a different issue then – Vijai Jan 08 '18 at 12:19