When I try to download a file from the PHP website it does not start downloading. I have added download listener. Whenever I try to download direct files from another website in webview it normally downloads but when I try to download via PHP site it does not download due to query string links of PHP.
Declare the string variable:
private String myFileName;
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition,
String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//myFileName = URLUtil.guessFileName(url,contentDisposition,mimeType);
myFileName = (contentDisposition.substring(contentDisposition.lastIndexOf(“myFileName*=UTF-8”)+17));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader(“cookie”,cookies);
request.addRequestHeader(“User-Agent”,userAgent);
request.setDescription(“Downloading File”);
request.setTitle(myFileName));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
myFileName);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
//Registering receiver in Download Manager
registerReceiver(onCompleted, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadManager.enqueue(request);
Toast.makeText(getApplicationContext(), “Downloading File…”, Toast.LENGTH_SHORT).show();
}
});
BroadcastReceiver onCompleted = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context.getApplicationContext(), “Download Finished”, Toast.LENGTH_SHORT).show();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + “/” + myFileName);
Uri uri = FileProvider.getUriForFile(WebViewActivity.this, “com.example.app”+”.provider”,file);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(uri, “application/pdf”);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(i);
}
};