简体   繁体   中英

How to create a new folder in root of SdCard on Android?

I want to create a new folder in Root or main page of SdCard. I have use this method to get SdCard location:

File("/storage/sdcard1", "New folder")

But this method didn't work on some devices. I need an method that work on all devices and get SdCard location.

I have also tried :

File(Environment.getExternalStorageDirectory(),"New folder")

But this method target device storage. But I want SdCard.

When you want to create the folder run the following line of code:

startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), 42);

Choose your SD card from the dialog that appears. The following method will get called after you have closed the dialog and inside there you can create your directory.

@Override 
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       switch (requestCode) {
                            // Check for the integer request code originally supplied to startResolutionForResult().
          case 42:

             if (resultCode != RESULT_OK)  return;

             if(data != null) { 
             Uri treeUri = data.getData();
             grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);                               
             getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
             DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri );
             DocumentFile myDirectory =  pickedDir.createDirectory("MyDirectory");
            }
          break;

       default:  break;
    }
}

PS1: 42 is a random number i use. Choose any unique positive integer instead of 42 if you like. Better even make it a constant.

PS2: In onActivityResult you can save the treeUri value to some variable,database,etc so everytime you need to create more folders or files in the SD root directory, you can have it readily available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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