WebView Download Manager: How to download files with their default names? - java

I'm developing a simple webview app using Android Studio. The webview app is booting a website that contains downloadable media files. For now, after downloading a file it save the file as fileName.
This is my Download manager
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();
}
});
}
I don't want it to be saving all files with the name "fileName". I want it to be saving files with their default names

You should somehow be able to get the file name from the url like so:
String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
Then just pass that in this line instead of hardcoded String "filename":
myRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);

Related

How to download and immediately open this file in another application

Good day. I am creating an application that downloads a file from firebase. Next, this file will have to open in the application that is installed in advance on the phone. How can I find this file after installation and open it in a new application. Thanks for any answer. sorry for my English
Download code:
public void downloadFiles(Context context, String fileName, String fileExtension, String destinationDirectory, String url) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(context, destinationDirectory, fileName + fileExtension);
downloadManager.enqueue(request);
What i tried.
open code:
public void openFile() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("file/*");
File download = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"king.mcpack");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(download));
startActivity(Intent.createChooser(intent, "Open with"));
}

Unable to download the pdf file from WebView. Always download .bin file. I checked in one plus mobile having android 10

I try to download file inside a WebView. File is downloaded using browser but when I try to download through mobile WebView. It is download as .bin file. I checked this in android 10 device. It is working in below android 10. I was using Advance WebView library to open the WebView. I am using below code for that. Any help will be highly appreciated.
#Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition,
mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File",
Toast.LENGTH_LONG).show();
Log.d("dsfgh", "onDownloadRequested: "+url);
}
In Kotlin, Work For Me
// coding download
webView.setDownloadListener { url, userAgent, contentDisposition, mimetype, _ ->
//checking Runtime permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
//Do this, if permission granted
downloadDialog(url, userAgent, contentDisposition, mimetype)
} else {
//Do this, if there is no permission
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
100
)
}
} else {
//Code for devices below API 23 or Marshmallow
downloadDialog(url, userAgent, contentDisposition, mimetype)
}
}
}
private fun downloadDialog(url: String?, userAgent: String?, contentDisposition: String?, mimetype: String?) {
//getting file name from url
val filename = URLUtil.guessFileName(url, contentDisposition, mimetype)
//Alertdialog
val builder = AlertDialog.Builder(this)
//title for AlertDialog
builder.setTitle("Download")
//message of AlertDialog
builder.setMessage("Do you want to save $filename")
//if YES button clicks
builder.setPositiveButton("Yes") { _, _ ->
//DownloadManager.Request created with url.
val request = DownloadManager.Request(Uri.parse(url))
//cookie
val cookie = CookieManager.getInstance().getCookie(url)
//Add cookie and User-Agent to request
request.addRequestHeader("Cookie", cookie)
request.addRequestHeader("User-Agent", userAgent)
//file mimetype
request.setMimeType(mimetype)
request.setTitle(URLUtil.guessFileName(url,contentDisposition,mimetype))
//file scanned by MediaScannar
request.allowScanningByMediaScanner()
//Download is visible and its progress, after completion too.
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
//DownloadManager created
val downloadmanager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
//Saving file in Download folder
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url,contentDisposition,mimetype))
//download enqued
downloadmanager.enqueue(request)
}
//If Cancel button clicks
builder.setNegativeButton("Cancel")
{ dialog, _ ->
//cancel the dialog if Cancel clicks
dialog.cancel()
}
val dialog: AlertDialog = builder.create()
//alertdialog shows
dialog.show()
}

Loading PDF from internal storage Error invalid format

So I've been practising download manager and i was trying out some program.
A first button will download a said Pdf to a location in my phone.
The second button is supposed to open the Pdf file with a Pdf reader installed by the user such as WP Reader etc..
The download works fine, but when i open the pdf , it says invalid format.
I uploaded a sample Pdf to the google drive , so I know that the uploaded file isnt corrupted in any case. There muse be some problem when the file is being downloaded from the server. Please help me find the mistake. And I am relatively new to Android.
And the download button uses an Onclicklistener while the loadPdf is given in the xml file android:onClick="downloadPdf" .
public class MainActivity extends AppCompatActivity {
String myHTTPUrl = "https://drive.google.com/open?id=0B5Pev9zz5bVjZTFFZ1dLZVp1WVU";
String TAG = "My app";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button download = (Button) findViewById(R.id.download);
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG,"download method called");
downloadPdf();
Toast.makeText(MainActivity.this,"Listener Called",Toast.LENGTH_SHORT).show();
Log.v(TAG,"On Click Listener Called");
}
});
}
public void loadPdf(View view) {
Log.v(TAG,"Pdf load called");
File pdfFile = new File(Environment.getExternalStorageDirectory()+"/notes","ssp.pdf");
if(pdfFile.exists())
{
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent intent = Intent.createChooser(pdfIntent, "Open File");
try
{
startActivity(intent);
}
catch(ActivityNotFoundException e)
{
Toast.makeText(MainActivity.this, "No Application available to view pdf", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(MainActivity.this,"Pdf not found",Toast.LENGTH_SHORT).show();
}
}
public void downloadPdf()
{
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myHTTPUrl));
request.setTitle("Solid State Physics");
request.setDescription("File is being Downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir("/notes","ssp.pdf");
manager.enqueue(request);
}}
EDITED :
This is the exact error I'm facing with screenshot
Error : File format error , Cannot be opened
Screenshot of the error.
You're not downloading the PDF, you're downloading the web-page displaying the contents of the PDF. If you want to download the PDF file directly, use the following URL:
String myHTTPUrl = "https://drive.google.com/uc?export=download&id=0B5Pev9zz5bVjZTFFZ1dLZVp1WVU";
and your application should work.
(Don't forget to delete the invalid notes/ssp.pdf file first, otherwise the DownloadManager will download the file under a different name, like notes/ssp-1.pdf.)

Download Manager is not showing file in Gallery after downloading from webview

I want to download image from my webview, a notification comes and it downloads the file but when i go to Gallery then the file is not there.What i'm doing wrong ... ??
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(geturl));
request.setTitle("File Download");
request.setDescription("File is being downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String nameOfFile = URLUtil.guessFileName(geturl, null, MimeTypeMap.getFileExtensionFromUrl(geturl));
request.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DCIM,nameOfFile);
DownloadManager manager = (DownloadManager)getApplication().getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
While geturl is the Override url by which i am taking the url of an image.
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//Get url for downloading
geturl = url;
return true;
}

How to set download directory in DownloadManager?

I am using DownloadManager but it puts the download somewhere I don't know. I want to download the file in a specific folder like "mp3" in sdcard.
Here is the code I am using :
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
if(url.endsWith(".mp3") || !url.startsWith("http://xnm")) {
String servicestring = Context.DOWNLOAD_SERVICE;
DownloadManager downloadmanager;
downloadmanager = (DownloadManager) getSystemService(servicestring);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new Request(uri);
Long reference = downloadmanager.enqueue(request);
setProgressBarIndeterminateVisibility(false);
}
else {
mWebView.loadUrl(url);
setProgressBarIndeterminateVisibility(true);
}
return true;
}
#Override
public void onPageFinished(WebView webview, String url){
super.onPageFinished(webview, url);
setProgressBarIndeterminateVisibility(false);
}
}
Thanks in advance !!
Use
File file = new File(Environment.getExternalStorageDirectory(), "mp3")
request.setDestinationUri(Uri.fromFile(file));
to set the download path
Actually I got it working after searching a lot and here it is the code to add in existing.
File folder = new File(Environment.getExternalStorageDirectory() + "/any");
if (!folder.exists()) {
folder.mkdir();
}
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDestinationInExternalPublicDir("/Download/Global Mp3", nameOfFile);
And we need this permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Thats it !!! Maybe it will help someone else
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);

Categories

Resources