Tony Starkus
Tony Starkus

Reputation: 576

How to Download a file in App with webview component?

I have a App with WebView, and i'm trying to download a file. I just want to download files, don't need be inside WebView App, just making the download. I search in the web some codes but i don't found much about this.

This is my WebView (the webview is a fragment):

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;

}

I tried this code:

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);
}
});

This code will open browser and make the download from it. The problem in this code is that the download start, but after that the download failed.

Upvotes: 0

Views: 4405

Answers (1)

diegoveloper
diegoveloper

Reputation: 103421

As I said, if you want to download the file inside your webview, you should try this:

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

    }
});

Don't forget to add this permission on your manifest:

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

And if you are using Android > 5 , you have to ask for permissions :)

Link: https://developer.android.com/training/permissions/requesting.html

Upvotes: 2

Related Questions