如何从WebView下载图像

时间:2017-04-30 06:36:49

标签: java android xml android-studio webview

我正在为APOD开发这个NASA OpenAPI应用程序,并为它建立了一个网站。我托管了它,一切正常。但我需要下载图像。我从AJAX调用中获取了图像URL

$("#a_tag_id").attr('href',result.hdurl);

然后在网站上制作了一个下载按钮,点击该按钮后会下载图像。

<center><button type="button" class="btn btn-primary"><a id="a_tag_id" download="apod.jpeg" style="color: white">Download the Image</a></button></center>

现在,完成此操作检查https://ck090.github.io/。我做了一个应用程序来显示相同​​的网站,因为它是响应。但是我无法下载图像。

我的android Main_Activity.java代码是:

package com.example.chandrakanth.adop;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.MimeTypeMap;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.File;
import java.lang.ref.Reference;

public class MainActivity extends AppCompatActivity {

    private WebView myWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);
        myWebView = (WebView)findViewById(R.id.webView);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
        webSettings.setDomStorageEnabled(true);
        // get from xml, with all size set "fill_parent"
        myWebView = (WebView) findViewById(R.id.webView);
        // fit the width of screen
        myWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // remove a weird white line on the right size
        myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("https://ck090.github.io/");
        myWebView.setWebViewClient(new WebViewClient());
    }

    /**
     * The webview client receives notifications about appView
     */
    public class ChildBrowserClient extends WebViewClient {
        @SuppressLint("InlinedApi")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            boolean value = true;
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);
            if (extension != null) {
                MimeTypeMap mime = MimeTypeMap.getSingleton();
                String mimeType = mime.getMimeTypeFromExtension(extension);
                if (mimeType != null) {
                    if (mimeType.toLowerCase().contains("video")
                            || extension.toLowerCase().contains("mov")
                            || extension.toLowerCase().contains("mp3")) {
                        DownloadManager mdDownloadManager = (DownloadManager) MainActivity.this
                                .getSystemService(Context.DOWNLOAD_SERVICE);
                        DownloadManager.Request request = new DownloadManager.Request(
                                Uri.parse(url));
                        File destinationFile = new File(
                                Environment.getExternalStorageDirectory(),
                                getFileName(url));
                        request.setDescription("Downloading via Your app name..");
                        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                        request.setDestinationUri(Uri.fromFile(destinationFile));
                        mdDownloadManager.enqueue(request);
                        value = false;
                    }
                }
                if (value) {
                    view.loadUrl(url);
                }
            }
            return value;
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
        /**
         * Notify the host application that a page has started loading.
         *
         * @param view
         *      The webview initiating the callback.
         * @param url
         *      The url of the page.
         */
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }
    }
    /**
     * File name from URL
     *
     * @param url
     * @return
     */
    public String getFileName(String url) {
        String filenameWithoutExtension = "";
        filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
                + ".mp4");
        return filenameWithoutExtension;
    }
}

和我的activity_main.xml文件是:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        tools:context=".MainActivity">

        <WebView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/webView"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </RelativeLayout>

最后我的Android_Manifest.xml文件是:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.chandrakanth.adop">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>

1 个答案:

答案 0 :(得分:1)

您需要setDownloadListener方法,例如参考Answer

myWebView .setDownloadListener(new DownloadListener() {

        public void onDownloadStart(String url, String userAgent,
            String contentDisposition, String mimetype,
                                       long contentLength) {

                Request request = new Request(Uri.parse(url));
                request.allowScanningByMediaScanner();

                    request.setNotificationVisibility(
                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

                    request.setDestinationInExternalPublicDir(
                    Environment.DIRECTORY_DOWNLOADS,    //Download folder
                    "download");                        //Name of file


                    DownloadManager dm = (DownloadManager) getSystemService(
                    DOWNLOAD_SERVICE);

                    dm.enqueue(request);  

        }
    });