如何在Android WebView中启动下载链接后自动关闭浏览器?

3
在我的WebView中,有几个间接下载链接看起来像是https://www.example.com/download/1234。当我在电脑浏览器上打开链接时,它会下载PDF文件。但是当我在WebView上点击链接时,它不会下载。
因此,我在我的WebView中设置了下载监听器,在onDownloadStart里使用startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); 它会启动一个浏览器,并开始下载PDF文件。浏览器会一直停留在那里,除非我按下手机的返回按钮。
如何在下载开始后自动关闭浏览器并返回到应用程序?

使用下载管理器而不是Webview...同时使用文件的完整路径。 - Dhaval Parmar
当有下载管理器时,您不想打开浏览器来从应用程序下载文件。请搜索“android downloadmanager webview”。 - CmosBattery
我已经尝试使用下载管理器,但是我得到的文件大小为0KB。我认为这是因为该文件没有扩展名,所以下载管理器下载了一个空白页面。 - taingmeng
2个回答

0
除非浏览器提供接口,否则我们无法在下载开始后自动关闭浏览器。 而你得到的文件大小为0KB的原因并不是文件没有扩展名。因为你只是从HTTP响应消息的响应内容中下载数据,这与扩展名无关。 因此,在使用DownloadManager时还存在另一个问题。

0
尝试使用下载管理器强制下载:使用此代码,希望能帮到你:
public void onDownloadStart(String aUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) {    
                    fileName = URLUtil.guessFileName(aUrl, contentDisposition, mimetype); //returns a string of the name of the file THE IMPORTANT PART
                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(aUrl));
                    request.allowScanningByMediaScanner();
                    CookieManager cookieManager = CookieManager.getInstance();
                    String cookie = cookieManager.getCookie(aUrl);
                    request.addRequestHeader("Cookie", cookie);
                    request.setMimeType("application/pdf");
                    request.addRequestHeader("User-Agent", userAgent);
                    Environment.getExternalStorageDirectory();
                    getActivity().getApplicationContext().getFilesDir().getPath(); //which returns the internal app files directory path
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
                    DownloadManager dm = (DownloadManager)getActivity(). getSystemService(DOWNLOAD_SERVICE);
                    dm.enqueue(request);

你可以添加广播接收器来在文件打开时打开它。 - Nawrez
你可以检查安全权限以读取外部存储,以防止在最新的Android版本中应用程序崩溃。 - Nawrez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接