[英]How to open pdf in my android app from file manager in android pie
[英]How to open my app documents directory with Android File Manager
我一直在尝试找出一种直接在我的应用程序的文档目录中打开 Android 文件管理器的方法,这样用户就可以 select 一个 JSON 文件,而无需用户 go 搜索文件路径 /storage/emulated/0/ Android/data/com.company.app/files/Documents/. 到目前为止,我可以使“自己去找”策略起作用,但不能使“将用户带到他们的目录”方法。 这是我尝试过的:
// this is the "go find it yourself" approach that I've used:
String filename = this.getResources().getString(R.string.ExportImportFileNameString);
File directory = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
Uri dirPathUri = Uri.fromFile(directory);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
Intent.createChooser(intent, "Open in...");
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, directory);
startActivityForResult(intent, IMPORT_REQUEST);
当为 IMPORT_REQUEST 调用我的 onActivityComplete 处理程序时,我看到返回的数据看起来像 dat=content://com.lge.filemanager.FileProvider/storage/emulated/0/Android/data/com.company.app/files/Documents/SelectedFile .json flg=0x1 }
我试图调用 intent.setDataAndType 的两种不同组合而不是 intent.setTypefollowing 并且无法让我 select 任何东西:
// This setDataAndType setup does not allow the user to open File Manager, nor navigate to the app Documents:
intent.setDataAndType(dirPath2, "application/json");
// This allows opening of File Manager but returns immediately without allowing the user to select a file, and returns a null data pointer:
intent.setDataAndType(dirPath2, "*/*");
请注意,我已尝试使用 ACTION_OPEN_DOCUMENT、ACTION_GET_CONTENT 和 ACTION_VIEW 创建意向 object,结果相似。 如果我只有一个文件,我知道我可以让应用程序简单地打开一个 stream 阅读器来获取已知文件名,如下所示:
File directory = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File importFile = new File(directory, filename);
try
{
fis = new FileInputStream (importFile);
InputStreamReader inputStreamReader =
new InputStreamReader(fis, StandardCharsets.UTF_8);
...
但是,这不允许我希望允许用户从多个文件访问 select 的灵活性。 任何人都可以阐明这里发生了什么以及如何纠正这种情况。
根据 Commonsware 反馈,以下是我对这个问题的解决方案:
//--------------
// Get the documents location for this app
File directory = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File desiredFilePath = new File(directory.toString());
try{
// read all pathnames for files and directory
File[] allFilesInDirectory = desiredFilePath.listFiles();
// prepare array to place all path strings into
ArrayList<String> filesInDirectoryArray = new ArrayList<String>();
// retrieve each pathname file array
// but someone could simply use the "path" object instead
for(File path:allFilesInDirectory){
if (path != null){
// put all file paths into string array
filesInDirectoryArray.add(path.getPath());
// could discriminate based on file extension, if so desired
}
}
// send file path array for processing
ProcessDocuments(filesInDirectoryArray);
}catch(SecurityException e){
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.