![](/img/trans.png)
[英]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.