Sun. Oct 21st, 2018

Downloading File From Android WebView

Hello Developers, Hope our posts at mytrendin are valuable for you.In this tutorial, you would learn about Downloading File inside Android WebView.

Downloading File inside Android WebView

When we open a URL, many times We need to Download a File or a pdf. Download Manager and Download Listener are responsible for performing this function. Wants to Learn Advanced Android Application development from scratch- Beyond Basics

Creating New Project  – LaunchApps

Step 1: – Creating Project

Open your Android Studio -> Create a new project -> Choose EmptyActivity > Finish

Step 2: – Creating activity_main

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.kartiksakhuja.download.MainActivity">
<WebView
android:id="@+id/wv"
android:background="@android:color/background_light"
android:layout_width="500dp"
android:layout_height="630dp" />

</RelativeLayout>

Step 3:- Creating MainActivity.java

In MainActivity.java, processes there is a DownloadListeprocessesthe request of DownloadManager. DownloadListener Overrides onDownloadStart in which five parameters are passed such as url, userAgent, ContentDisposition, mimeType, contentLength that specifies the format of file, maximum data that can be downloaded.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


import android.app.DownloadManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
WebView wv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView) findViewById(R.id.wv);

wv.loadUrl("http://cbseacademic.in/SQP_CLASSXII_2016_17.html");
wv.setWebViewClient(new MyClient());
wv.setWebChromeClient(new GoogleClient());
WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wv.clearCache(true);
wv.clearHistory();
wv.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));


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.setDestinationInExternalFilesDir(MainActivity.this,
Environment.DIRECTORY_DOWNLOADS,".pdf");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File",
Toast.LENGTH_LONG).show();
}});


wv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
wv.loadUrl("http://cbseacademic.in/SQP_CLASSXII_2016_17.html");
}
});


}

class MyClient extends WebViewClient
{

@Override
public void onPageStarted(WebView view,String url,Bitmap favicon){
super.onPageStarted(view,url,favicon);

}
@Override
public boolean shouldOverrideUrlLoading(WebView view,String Url)
{
view.loadUrl(Url);
return true;

}
@Override
public void onPageFinished(WebView view,String url)
{
super.onPageFinished(view,url);

}
}
class GoogleClient extends WebChromeClient
{
@Override
public void onProgressChanged(WebView view,int newProgress)
{
super.onProgressChanged(view,newProgress);

}
}
@Override
public void onBackPressed() {
if (wv.canGoBack())
wv.goBack();
else
super.onBackPressed();

}
}

Related:

5 best Free Internet download manager for windows

Uploading file to Google Drive in Android Application

How to read PDF files in android

Play a music file in background using services

Android Pick File Programatically

Step 4:- Adding Permissions to AndroidManifest.xml and after adding permission it should look like this:-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kartiksakhuja.download">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

 

Output:-

                                                

Thanks for following our Android WebView tutorials.If you have any queries fell free to ask us in the comment section.Do not forget to Subscribe to all the latest technical happenings. If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

10 thoughts on “Downloading File From Android WebView

  1. THANK FOR IT
    I AM NEW DEVELOPER AND I FIND THIS SOLUTION FOR LAST SUM MONTH,
    I WAS TRIED SO MEANY TRICK BUT it was NOT WORK PROPERLY

  2. i want to download pdf file from webview but not getting proper url in shouldOverrideUrlLoading this method but same webpage is working fine on device browser please let me know where i can fire intent to download pdf
    Thanks

  3. when i click on print option on pdf still that download pdf but at that time i want to print preview .
    So is there any idea about that for webview.

Leave a Reply

Your email address will not be published. Required fields are marked *