Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open specific folder using Intent

I want to open specific path folder using Intent, I used code for File explorer and It working perfectly but in some device (samsung devices) if file explorer app are not available then It not opening folder of specific path. I tried many solutions but It won't work for me.

Uri uri = Uri.fromFile(new File(new File(filePath).getParent()));
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "resource/folder");


        if (intent.resolveActivityInfo(getPackageManager(), 0) != null)
        {
            startActivity(intent);
        }
        else {

           Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
           intent.setDataAndType(uri, "file/*");
           startActivity(Intent.createChooser(intent, "Open folder"));

        }
like image 400
Nik Avatar asked Jul 27 '17 05:07

Nik


2 Answers

        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.setDataAndType(
            Uri.parse(
                (Environment.getExternalStorageDirectory().path
                        + java.io.File.separator) + "myFile" + java.io.File.separator
            ), "*/*"
        )
        intent.addFlags(
            Intent.FLAG_GRANT_READ_URI_PERMISSION
                    and Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                    and Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
                    and Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
        )
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        startActivityForResult(intent, WRITE_ACCESS_CODE)
like image 190
Sanush Avatar answered Sep 26 '22 16:09

Sanush


Here is my solution for accessing "root/Downloads/Sam" in Kotlin

val rootPath = "content://com.android.externalstorage.documents/document/primary:"
val samPath = Uri.parse("$rootPath${Environment.DIRECTORY_DOWNLOADS}%2fSam")    //"%2f" represents "/"

val REQUEST_CODE_PICK_FILE = 1

main_sam_button.setOnClickListener {
    val intent = Intent(Intent.ACTION_GET_CONTENT)                                  

    intent.type = "text/plain"    //specify file type
    intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, samPath)    //set the default folder

    startActivityForResult(intent, REQUEST_CODE_PICK_FILE)
}

Demo: https://youtu.be/lUIPyC_8q_M


Helpful reading:

  • "content://com.android.externalstorage.documents/document/primary:": What is com.android.externalstorage?
like image 43
Sam Chen Avatar answered Sep 24 '22 16:09

Sam Chen