2012-04-09 16 views
45

Tengo una vista web en mi aplicación de Android. Cuando el usuario va a la vista web y hace clic en un enlace para descargar un archivo, no ocurre nada.Descargar archivo dentro de WebView

URL = "my url"; 
mWebView = (WebView) findViewById(R.id.webview); 
mWebView.setWebViewClient(new HelloWebViewClient()); 
mWebView.getSettings().setDefaultZoom(ZoomDensity.FAR); 
mWebView.loadUrl(URL); 
Log.v("TheURL", URL); 

¿Cómo habilitar la descarga dentro de una página web? Si deshabilito la vista web y habilito la intención de cargar la URL en el navegador desde la aplicación, la descarga funciona sin problemas.

String url = "my url"; 
Intent i = new Intent(Intent.ACTION_VIEW); 
i.setData(Uri.parse(url)); 
startActivity(i); 

¿Alguien me puede ayudar aquí? La página se carga sin problema pero el enlace a un archivo de imagen en la página HTML no funciona ...

+0

Esta herramienta puede emplearse 'subclase Webview' que se ocupa de descargas, etc automáticamente: https://github.com/delight-im/Android-AdvancedWebView – caw

Respuesta

64

¿Lo intentó?

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

Esto simplemente vuelve a cargar la página HTML en el navegador. Sería más agradable si la URL del archivo adjunto se abre en el navegador ... Gracias por la respuesta. Valorarlo. –

+0

¿Puedes publicar tu url? – user370305

+0

http://demo.rdmsonline.net/incidentinfo.aspx?incid=la%2fMDMOBS4VeBNKk6yNz%2fg%3d%3d esta es mi url –

15

Pruebe con el administrador de descargas, que puede ayudarlo a descargar todo lo que desee y le ahorrará tiempo.

Comprobar aquellos a opciones:

Opción 1 ->

mWebView.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"); 
        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); 
        dm.enqueue(request);   

     } 
    }); 

Opción 2 ->

if(mWebview.getUrl().contains(".mp3") { 
Request request = new Request(
         Uri.parse(url)); 
       request.allowScanningByMediaScanner(); 
       request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
       request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download"); 
// You can change the name of the downloads, by changing "download" to everything you want, such as the mWebview title... 
       DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); 
       dm.enqueue(request);   

    } 
31

probar esto. Después de pasar por muchas publicaciones y foros, encontré esto.

mWebView.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); //Notify client once download is completed! 
      request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Name of your downloadble file goes here, example: Mathematics II "); 
      DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); 
      dm.enqueue(request); 
      Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded 
        Toast.LENGTH_LONG).show(); 

     } 
    }); 

¡No olvide dar este permiso! ¡Esto es muy importante! Agregue esto en su archivo de Manifiesto (El archivo AndroidManifest.xml)

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  <!-- for your file, say a pdf to work --> 

Espero que esto ayude. Saludos :)

+8

¡Gracias funcionó !: para usar el nombre original del archivo, podemos usar: 'final String filename = URLUtil.guessFileName (url, contentDisposition, mimetype);' – Jawaad

+7

@SaiZ su ejemplo contiene algún código sobre un intento no utilizado, supongo que debería eliminarlo –

+0

@ j.c eliminé el código no utilizado, gracias por informarlo;) – MatPag

7
mwebView.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.setDestinationInExternalPublicDir(
      Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
        url, contentDisposition, mimeType)); 
    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); 
    dm.enqueue(request); 
    Toast.makeText(getApplicationContext(), "Downloading File", 
      Toast.LENGTH_LONG).show(); 
}}); 
+0

por favor explique lo que escribió. solo el código no es suficiente – Saveen

+0

¡Configurar cookies guardadas mi día! ¡Gracias! –