如何使用webview组件在App中下载文件?

时间:2017-11-15 22:24:23

标签: android webview

我有一个使用WebView的应用程序,我正在尝试下载文件。 我只想下载文件,不需要在WebView App中,只需下载即可。我在网上搜索了一些代码,但我对此没有太多了解。

这是我的WebView(webview是一个片段):

public class Example extends Fragment {

public WebView myWebView;

private ProgressBar prg;

SwipeRefreshLayout mySwipeRefreshLayout;


public static Example newInstance() {
    Example fragment = new Example();
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View rootView = inflater.inflate(R.layout.pagina_principal_layout, container, false);
    myWebView = (WebView) rootView.findViewById(R.id.paginaPrincipalWebView);
    myWebView.loadUrl("http://example.com/");
    prg = (ProgressBar)rootView.findViewById(R.id.progressBar2);
    mySwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipelayout);

    //Esconder barra deslizante lateral de navegação Web.
    myWebView.setVerticalScrollBarEnabled(false);


    //*Ativar JavaScript
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);


    //*Forçar links para abrir no WebView ao invés do navegador
    myWebView.setWebViewClient(new WebViewClient());


    //Forçar links para abrir no WebView ao invés do navegador.
    mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            myWebView.reload();
            mySwipeRefreshLayout.setRefreshing(false);
        }
    });


    //*Voltar histórico ao pressionar botão "voltar"
    myWebView.setOnKeyListener(new View.OnKeyListener()
    {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if(event.getAction() == KeyEvent.ACTION_DOWN)
            {
                WebView webView = (WebView) v;

                switch(keyCode)
                {
                    case KeyEvent.KEYCODE_BACK:
                        if(webView.canGoBack())
                        {
                            webView.goBack();
                            return true;
                        }
                        break;
                }
            }

            return false;
        }
    });



    return rootView;

}

我试过这段代码:

mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
            String contentDisposition, String mimetype,
            long contentLength) {
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
}
});

此代码将打开浏览器并从中进行下载。此代码中的问题是下载开始,但之后下载失败。

1 个答案:

答案 0 :(得分:2)

正如我所说,如果你想在webview中下载文件,你应该试试这个:

myWebView.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.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name of your file");
        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        dm.enqueue(request);
       //you could show a message here

    }
});

不要忘记在您的清单上添加此权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

如果您使用的是Android&gt; 5,你必须要求权限:)

链接:https://developer.android.com/training/permissions/requesting.html