Android: ¿Cómo abrir una carpeta específica a través de Intent y mostrar su contenido en un navegador de archivos?


Pensé que esto sería fácil, pero resulta que desafortunadamente no lo es.

Lo que tengo:

Tengo una carpeta llamada "myFolder" en mi almacenamiento externo (no tarjeta SD porque es un Nexus 4, pero ese no debería ser el problema). La carpeta contiene algunos archivos *.csv.

Lo que quiero:

Quiero escribir un método que haga lo siguiente: Mostrar una variedad de aplicaciones (navegadores de archivos) de las que puedo elegir una (ver imagen). Después de hacer clic en él, el el explorador de archivos seleccionado debe comenzar y mostrarme el contenido de "myFolder". Ni más ni menos.

introduzca la descripción de la imagen aquí

Mi pregunta:

¿Cómo hago eso exactamente? Creo que me acerqué bastante con el siguiente código, pero no importa lo que haga, y estoy seguro de que debe haber algo que aún no hice bien, siempre abre solo la carpeta principal del almacenamiento externo.

public void openFolder()
{
File file = new File(Environment.getExternalStorageDirectory(),
    "myFolder");

Log.d("path", file.toString());

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(file), "*/*");
startActivity(intent);
}
Author: kaolick, 2013-06-18

8 answers

Esto debería funcionar:

Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + "/myFolder/");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");

if (intent.resolveActivityInfo(getPackageManager(), 0) != null)
{
    startActivity(intent);
}
else
{
    // if you reach this place, it means there is no any file 
    // explorer app installed on your device
}

Por favor, asegúrese de tener cualquier aplicación de explorador de archivos instalada en su dispositivo.

EDITAR: se agregó una recomendación de shantanu del comentario.

BIBLIOTECAS : También puede echar un vistazo a estas bibliotecas de selectores de archivos/directorios https://android-arsenal.com/tag/35 si la solución actual no le ayuda.

 53
Author: Sa Qada,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-23 08:43:37

Finalmente lo conseguí. De esta manera, el selector solo muestra algunas aplicaciones (Google Drive, Dropbox, Root Explorer y Solid Explorer). Está funcionando bien con los dos exploradores, pero no con Google Drive y Dropbox (supongo que porque no pueden acceder al almacenamiento externo). El otro tipo MIME como "*/*" también es posible.

public void openFolder(){
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
         +  File.separator + "myFolder" + File.separator);
    intent.setDataAndType(uri, "text/csv");
    startActivity(Intent.createChooser(intent, "Open folder"));
}
 36
Author: kaolick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-08 13:13:23
Intent chooser = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getDownloadCacheDirectory().getPath().toString());
chooser.addCategory(Intent.CATEGORY_OPENABLE);
chooser.setDataAndType(uri, "*/*");
// startActivity(chooser);
try {
startActivityForResult(chooser, SELECT_FILE);
}
catch (android.content.ActivityNotFoundException ex)
{
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}

En el código anterior, si setDataAndType es "*/*" se abre un navegador de archivos integrado para elegir cualquier archivo, si establezco "texto/plano" se abre Dropbox. Tengo Dropbox, Google Drive instalado. Si desinstalo Dropbox solo "* / * " funciona para abrir el navegador de archivos. Esto es Android 4.4.2. Puedo descargar contenidos desde Dropbox y para Google Drive, mediante getContentResolver ().openInputStream (data.getData ()).

 3
Author: WayneSplatter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-11 09:11:40

Este código funcionará con el Administrador de archivos OI:

        File root = new File(Environment.getExternalStorageDirectory().getPath()
+ "/myFolder/");
        Uri uri = Uri.fromFile(root);

        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setData(uri);
        startActivityForResult(intent, 1);

Puede obtener el administrador de archivos OI aquí: http://www.openintents.org/en/filemanager

 1
Author: Abtin tashakor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-21 06:58:16
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

intent.setType("text/csv");

intent.addCategory(Intent.CATEGORY_OPENABLE);

try {
      startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 0);

} catch (android.content.ActivityNotFoundException ex) {
  ex.printStackTrace();
}

Entonces solo necesita agregar la respuesta

public void  onActivityResult(int requestCode, int resultCode, Intent data){

switch (requestCode) {
  case 0: {
     //what you want to do
    //file = new File(uri.getPath());
  }
}
}
 0
Author: Renato Martins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-10 16:41:42

Hoy en día, debería representar una carpeta utilizando su URI de contenido obtenido del Marco de Acceso a almacenamiento, y abrirla debería ser tan simple como:

Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);

Por desgracia, la aplicación Archivos contiene actualmente un error que hace que se bloquee cuando intenta esto utilizando el proveedor de almacenamiento externo. Sin embargo, las carpetas de terceros proveedores se pueden mostrar de esta manera.

 0
Author: j__m,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-03 13:13:13
File temp = File.createTempFile("preview", ".png" );
String fullfileName= temp.getAbsolutePath();
final String fileName = Uri.parse(fullfileName)
                    .getLastPathSegment();
final String filePath = fullfileName.
                     substring(0,fullfileName.lastIndexOf(File.separator));
Log.d("filePath", "filePath: " + filePath);

FullfileName :

/mnt/sdcard/Download_Manager_Farsi/preview.png

Ruta de archivo :

/mnt/sdcard / Download_Manager_Farsi

 -1
Author: Iman Marashi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-07 23:07:12

Pareces cercano.

Intentaría establecer el URI de esta manera:

String folderPath = Environment.getExternalStorageDirectory()+"/pathTo/folder";

Intent intent = new Intent();  
intent.setAction(Intent.ACTION_GET_CONTENT);
Uri myUri = Uri.parse(folderPath);
intent.setDataAndType(myUri , "file/*");   
startActivity(intent);

Pero no es tan diferente de lo que has intentado. Dinos si cambia algo.

También asegúrese de que la carpeta de destino existe, y echar un vistazo a la resultante Uri objeto antes de enviarlo a la intent, puede que no sea lo que se espera.

 -1
Author: Guian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-19 09:16:06