java - 从 Android 的下载文件夹中获取 pdf 或 doc 文件

标签 java android android-studio

我正在尝试多种方法来打开用户的下载文件夹并允许用户只选择要打开的 doc 或 pdf 文件。那里的大多数方法已被弃用,它们的替代方法似乎对我不起作用。
当前代码:

// I've heavily altered the code but hope you guys understand the gist of it.


//Steps:
// Open the Downloads folder 
// Let user select the pdf or docx.
// Open the doc or pdf.

        // Adding Syllabus Function Method Here.
        addSyllabus = findViewById(R.id.add_syllabus_button);
        addSyllabus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webview = (WebView) findViewById(R.id.webView);
                progressbar = (ProgressBar) findViewById(R.id.progressBar);
                webview.getSettings().setJavaScriptEnabled(true);
                String filename = "https://s25.q4cdn.com/967830246/files/doc_downloads/test.pdf";
                webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);
                webview.setWebViewClient(new WebViewClient() {

                    public void onPageFinished(WebView view, String url) {
                        // do your stuff here
                        progressbar.setVisibility(View.GONE);
                    }
                });
            }

        });
欣赏它,谢谢。

最佳答案

一个 Intent来自 DocumentsProvider可能是你最好的选择。
从此Google Guide :

private void openFile(Uri pickerInitialUri) {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("application/pdf");

    // Optionally, specify a URI for the file that should appear in the
    // system file picker when it loads.
    intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);

    startActivityForResult(intent, PICK_PDF_FILE);
您可以使用 setType如图所示,如果你想默认下载,你可以使用 putExtra如图所示。更改pickerInitialUri到正确的 URI,我认为它可以作为常量找到: Environment.DIRECTORY_DOWNLOADS .
更新:我现在意识到您想要的文件类型不止一种。根据 this thread :
您可以使用:
String [] mimeTypes = {"application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"};
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
(我从 mozilla 获得了 MIME 类型字符串。)

关于java - 从 Android 的下载文件夹中获取 pdf 或 doc 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65224666/

相关文章:

java - 使用字符串变量创建主屏幕的新实例

java - 为颜色方法提供默认字符串

android - Observable 在 Kotlin 中列出

android - Android Studio 4.1 中的 navigation.json 是什么?

Android Studio-构建失败

java - 需要帮助来理解 JUnit RunListener

java - 使用 wakelock.release() 关闭应用程序时 Android 应用程序崩溃

java - 如何使用递归创建二进制搜索算法

android - 是否可以从 Android 中的适配器获取对 ListView 的引用?

android - Android Studio 中 Android 应用的 Google Play 许可