Easy Tutorial
❮ Js Filter Dropdown Android Tutorial Bitmap2 ❯

7.5.4 WebView File Download

Category Android Basic Tutorial

Introduction

>

This section introduces the concept of file downloading in WebView. When using a regular browser like UC, clicking on a downloadable link initiates the download process. WebView, acting as a browser component, also supports file downloads. You can customize the download process, specify where and under what name the file should be saved, or use other built-in browsers like Chrome or UC for downloading. Below is a demonstration of its usage!


1. Using Other Browsers to Download Files:

>

This is straightforward. We just need to set a DownloadListener for the WebView and override the onDownloadStart method within DownloadListener. Then, create an Intent and start the corresponding Activity.

Key Code:

wView.setDownloadListener(new DownloadListener(){
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, 
    String mimetype, long contentLength) {
        Log.e("HEHE","Download started");
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW,uri);
        startActivity(intent);
    }
});

If multiple browsers are installed on your phone, a dialog will appear allowing you to choose one for the download.


2. Writing a Thread to Download Files

>

If you prefer not to use the default path for downloaded files or want to customize the file name, you can write a thread to handle the download. Here's an example implementation:

Core Code:

We create a separate download thread class:

DownLoadThread.java

/**
 * Created by Jay on 2015/9/14 0014.
 */
public class DownLoadThread implements Runnable {

    private String dlUrl;

    public DownLoadThread(String dlUrl) {
        this.dlUrl = dlUrl;
    }

    @Override
    public void run() {
        Log.e("HEHE", "Download started~~~~~");
        InputStream in = null;
        FileOutputStream fout = null;
        try {
            URL httpUrl = new URL(dlUrl);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            in = conn.getInputStream();
            File downloadFile, sdFile;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Log.e("HEHE","SD card writable");
                downloadFile = Environment.getExternalStorageDirectory();
                sdFile = new File(downloadFile, "csdn_client.apk");
                fout = new FileOutputStream(sdFile);
            }else{
                Log.e("HEHE","SD card not present or not writable");
            }
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) != -1) {
                fout.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fout != null) {
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Log.e("HEHE", "Download completed~~~~");
    }
}

Then, in MainActivity.java, create and start the thread:

wView.setDownloadListener(new DownloadListener(){
    @Override
    public void onDownloadStart(String url, String userAgent, String contentDisposition, 
    String mimetype, long contentLength) {
            Log.e("HEHE","onDownloadStart called: Download link: " + url);
            new Thread(new DownLoadThread(url)).start();
    }
});

Result:

Upon opening the SD card, you can see the downloaded file has been saved there:

Notes:

Remember to include permissions for SD card read/write and internet access:

<uses-permission android:name="android.permission.INTERNET"/>
<!-- Permission to create and delete files on the SD card -->
&lt;uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- Permission to write to the SD card -->
&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Also, ensure in = conn.getInputStream() is placed after all connection settings are configured; otherwise, it may not read anything!


Summary:

>

This section is quite simple; the key is using setDownloadListener and overriding the onDownloadStart method to handle the download process. That's all for this section, thank you!

-1.0 Android Basic Tutorial

-1.0.1 2015 Latest Android Basic Tutorial Contents

-1.1 Background and System Architecture Analysis

-1.2 Development Environment Setup

-1.2.1 Developing Android Apps with Eclipse + ADT + SDK

-1.2.2 Developing Android Apps with Android Studio

-1.3 Solving SDK Update Issues

-1.4 Genymotion Emulator Installation

-1.5.1 Git Tutorial: Basic Operations on Local Repositories

-1.5.2 Git: Setting Up a Remote Repository on GitHub

-1.6 How to Use 9-Patch Images

-1.7 Interface Prototype Design

-1.8 Project Source Analysis (Various Files, Resource Access)

-1.9 Signing and Packaging Android Applications

-1.11 Decompiling APK to Retrieve Code & Resources

-2.1 Concepts of View and ViewGroup

-2.2.1 LinearLayout (Linear Layout)

-2.2.2 RelativeLayout (Relative Layout)

-2.2.3 TableLayout (Table Layout)

-2.2.4 FrameLayout (Frame Layout)

-2.2.5 GridLayout (Grid Layout)

-2.2.6 AbsoluteLayout (Absolute Layout)

-2.3.1 Detailed Explanation of TextView (Text Box)

WeChat Subscription

❮ Js Filter Dropdown Android Tutorial Bitmap2 ❯