简体   繁体   English

Android:如何通过 Intent 打开特定文件夹并在文件浏览器中显示其内容?

[英]Android: How to open a specific folder via Intent and show its content in a file browser?

I thought this would be easy but as it turns out unfortunately it's not.我认为这很容易,但不幸的是事实并非如此。

What I have:我有什么:

I have a folder called "myFolder" on my external storage (not sd card because it's a Nexus 4, but that should not be the problem).我的外部存储设备上有一个名为“myFolder”的文件夹(不是 SD 卡,因为它是 Nexus 4,但这应该不是问题)。 The folder contains some *.csv files.该文件夹包含一些*.csv文件。

What I want:我想要的是:

I want to write a method which does the following: Show a variety of apps (file browsers) from which I can pick one (see picture).我想编写一种执行以下操作的方法:显示各种应用程序(文件浏览器),我可以从中选择一个(见图)。 After I click on it, the selected file browser should start and show me the content of "myFolder".单击它后,所选文件浏览器应启动并向我显示“myFolder”的内容。 No more no less.不多不少。

在此处输入图片说明

My question:我的问题:

How exactly do I do that?我该怎么做? I think I came quite close with the following code, but no matter what I do - and I'm certain that there must be something I didn't get right yet - it always opens only the main folder from the external storage.我想我对以下代码非常接近,但无论我做什么 - 而且我确信一定有我没有做对的事情 - 它总是只打开外部存储中的主文件夹。

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);
}

This should work:这应该有效:

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
}

Please, be sure that you have any file explorer app installed on your device.请确保您的设备上安装了任何文件浏览器应用程序。

EDIT: added a shantanu's recommendation from the comment.编辑:从评论中添加了 shantanu 的建议。

LIBRARIES : You can also have a look at the following libraries https://android-arsenal.com/tag/35 if the current solution doesn't help you.:如果当前的解决方案对您没有帮助,您还可以查看以下库https://android-arsenal.com/tag/35

I finally got it working.我终于让它工作了。 This way only a few apps are shown by the chooser (Google Drive, Dropbox, Root Explorer, and Solid Explorer).这样,选择器只会显示少数应用程序(Google Drive、Dropbox、Root Explorer 和 Solid Explorer)。 It's working fine with the two explorers but not with Google Drive and Dropbox (I guess because they cannot access the external storage).它在两个资源管理器上运行良好,但不适用于 Google Drive 和 Dropbox(我猜是因为它们无法访问外部存储)。 The other MIME type like "*/*" is also possible.其他 MIME 类型如"*/*"也是可能的。

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"));
}
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();
}

In code above, if setDataAndType is "*/*" a builtin file browser is opened to pick any file, if I set "text/plain" Dropbox is opened.在上面的代码中,如果 setDataAndType 为“*/*”,则打开内置文件浏览器以选择任何文件,如果我设置为“text/plain”,则打开 Dropbox。 I have Dropbox, Google Drive installed.我安装了 Dropbox、Google Drive。 If I uninstall Dropbox only "*/*" works to open file browser.如果我卸载 Dropbox,只有“*/*”可以打开文件浏览器。 This is Android 4.4.2.这是安卓 4.4.2。 I can download contents from Dropbox and for Google Drive, by getContentResolver().openInputStream(data.getData()).我可以通过 getContentResolver().openInputStream(data.getData()) 从 Dropbox 和 Google Drive 下载内容。

Thread is old but I needed this kind of feature in my application and I found a way to do it so I decided to post it if it can help anyone in my situation. Thread 很旧,但我的应用程序中需要这种功能,我找到了一种方法,所以我决定发布它,如果它可以帮助我的情况下的任何人。

As our device fleet is composed only by Samsung Galaxy Tab 2, I just had to find the file explorer's package name, give the right path and I succeed open my file explorer where I wanted to.由于我们的设备组仅由 Samsung Galaxy Tab 2 组成,我只需要找到文件浏览器的包名称,提供正确的路径,然后我就可以在我想要的地方成功打开我的文件浏览器。 I wish I could use Intent.CATEGORY_APP_FILES but it is only available in API 29.我希望我可以使用Intent.CATEGORY_APP_FILES但它仅在 API 29 中可用。

  Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.sec.android.app.myfiles");
  Uri uri = Uri.parse(rootPath);
  if (intent != null) {
      intent.setData(uri);
      startActivity(intent);
  }

As I said, it was easy for me because our clients have the same device but it may help others to find a workaround for their own situation.正如我所说,这对我来说很容易,因为我们的客户拥有相同的设备,但它可能会帮助其他人找到适合自己情况的解决方法。

this code will work with OI File Manager :此代码将与 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);

you can get OI File manager here : http://www.openintents.org/en/filemanager你可以在这里获得 OI 文件管理器: http : //www.openintents.org/en/filemanager

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, DocumentsContract.Document.MIME_TYPE_DIR);
startActivity(intent);

Will open files app home screen将打开文件应用程序主屏幕在此处输入图片说明

Here is my answer这是我的答案

private fun openFolder() {
    val location = "/storage/emulated/0/Download/";
    val intent = Intent(Intent.ACTION_VIEW)
    val myDir: Uri = FileProvider.getUriForFile(context, context.applicationContext.packageName + ".provider", File(location))
    intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        intent.setDataAndType(myDir,  DocumentsContract.Document.MIME_TYPE_DIR)
    else  intent.setDataAndType(myDir,  "*/*")

    if (intent.resolveActivityInfo(context.packageManager, 0) != null)
    {
        context.startActivity(intent)
    }
    else
    {
        // if you reach this place, it means there is no any file
        // explorer app installed on your device
        CustomToast.toastIt(context,context.getString(R.string.there_is_no_file_explorer_app_present_text))
    }
}

Here why I used FileProvider - android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()这里为什么我使用 FileProvider - android.os.FileUriExposedException: file:///storage/emulated/0/test.txt 通过 Intent.getData() 暴露在应用程序之外

I tested on this device我在这个设备上测试过
Devices: Samsung SM-G950F (dreamltexx), Os API Level: 28设备:三星 SM-G950F (dreamltexx),操作系统 API 级别:28

Today, you should be representing a folder using its content: URI as obtained from the Storage Access Framework, and opening it should be as simple as:今天,您应该使用从存储访问框架获得的内容来表示一个文件夹:URI,打开它应该很简单:

Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
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();
}

then you just need to add the response那么你只需要添加响应

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

switch (requestCode) {
  case 0: {
     //what you want to do
    //file = new File(uri.getPath());
  }
}
}

You seem close.你看起来很亲近。

I would try to set the URI like this :我会尝试像这样设置 URI:

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);

But it's not so different from what you have tried.但这与您尝试过的并没有太大不同。 Tell us if it changes anything ?告诉我们它是否改变了什么?

Also make sure the targeted folder exists, and have a look on the resulting Uri object before to send it to the intent , it may not be what we are expected.还要确保目标文件夹存在,并在将其发送到Intent之前查看生成的Uri对象,它可能不是我们所期望的。

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 /mnt/sdcard/Download_Manager_Farsi/preview.png

filePath :文件路径

/mnt/sdcard/Download_Manager_Farsi /mnt/sdcard/Download_Manager_Farsi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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