java - WebView下载管理器: How to download files with their default names?

标签 java android

我正在使用 Android Studio 开发一个简单的 webview 应用程序。 webview 应用程序正在启动一个包含可下载媒体文件的网站。现在,下载文件后,它将文件保存为 fileName。 这是我的下载管理器

        String myCurrentUrl;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    superWebView = findViewById(R.id.myWebView);

    superProgressBar.setMax(100);

    superWebView.loadUrl("http://www.hausadownload.blogspot.com");
    superWebView.getSettings().setJavaScriptEnabled(true);
    superWebView.setWebViewClient(new WebViewClient(){});
    superWebView.setWebChromeClient(new WebChromeClient());


    superWebView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {

            DownloadManager.Request myRequest = new DownloadManager.Request(Uri.parse(url));
            myRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "fileName");
            myRequest.allowScanningByMediaScanner();
            myRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            DownloadManager myManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            myManager.enqueue(myRequest);

            Toast.makeText(MainActivity.this, "Your file is downloading...", Toast.LENGTH_SHORT).show();
        }
    });

}

我不希望它保存所有名为“fileName”的文件。我希望它以默认名称保存文件

最佳答案

您应该能够从 url 中获取文件名,如下所示:

String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());

然后只需在这一行中传递它,而不是硬编码字符串“filename”:

myRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);

关于java - WebView下载管理器: How to download files with their default names?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52709432/

相关文章:

android - Activity 无法解析或不是字段

android - 使波纹填充整个 View

Android id命名约定: lower case with underscore vs.驼峰式

Java - 如何仅接受日期输入的整数?

java - 如何在没有在 application.properties 中设置的情况下获取 Controller 中的上下文路径

Java 版本的 mongo 查询,用于从数组中检索唯一字符串以及计数

java - Java 和内存中的指针

android - Android 2.1 和 2.2 之间的 SQLite 差异

java - PreparedStatement 可以不考虑 WHERE 子句中的某些条件吗?

android - 工具栏字幕被剪切(不适合高度)