Force access to external removable microSD card

后端 未结 3 1575
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 18:26

I\'m using a Samsung A3, Android 5.0.2. I\'m using this setup to compile apps, i.e. Android 4.1 Jelly Bean (API 16) target.

I precisely know the path of the external rem

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-05 19:17

    bear in mind that some android devices will have a different path for the SD Card and some doesn´t have removable SD Card.

    You don´t have to set the path directly!

    File myDir = new File("/mnt/extSdCard/test");
    myDir.mkdirs();
    

    You can check first if your device has mounted a removable SD Card:

    public static boolean isSDCardAvailable(Context context) {
        File[] storages = ContextCompat.getExternalFilesDirs(context, null);
        if (storages.length > 1 && storages[0] != null && storages[1] != null)
            return true;
        else
            return false;
    }
    

    Why get External Directories > 1, well because most of all the android devices has external storage as a primary directory and removable SD Card as second directory:

    But you can use a method to get the real path of your removable microSD card:

    public static String getRemovableSDCardPath(Context context) {
        File[] storages = ContextCompat.getExternalFilesDirs(context, null);
        if (storages.length > 1 && storages[0] != null && storages[1] != null)
            return storages[1].toString();
        else
            return "";
    }
    

    Then just do this:

    File myDir = new File(getRemovableSDCardPath(getApplicationContext()),"test");
    if(myDir.mkdirs()){
      Log.i(TAG, "Directory was succesfully create!");
    }else{
      Log.i(TAG, "Error creating directory!");
    }
    

    For example using the method:

       String pathSDCard = getRemovableSDCardPath(getApplicationContext());
    

    I have as a result the path of my removable SD Card (if i wouldn´t have a removable SD Card my path would be "", so you can implemente a validation to avoid the creation of the folder):

    /storage/extSdCard/Android/data/com.jorgesys.myapplication/files
    

    Now creating a new folder inside :

        File myDir = new File(getRemovableSDCardPath(getApplicationContext()),"test");
        if(myDir.mkdirs()){
            Log.i(TAG, "Directory was succesfully create!");
        }else{
            Log.i(TAG, "Error creating directory!");
        }
    

    now i have the directory /test created:

提交回复
热议问题