我怎样才能下载使用web视图文件? (已搜索的答案,但这种情况下是奇怪) [英] How can I download the file by using webview? (Already search for the answer but this case is wierd)

查看:194
本文介绍了我怎样才能下载使用web视图文件? (已搜索的答案,但这种情况下是奇怪)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用web视图从网站下载的文件(如MP3播放) 但问题是,当我点击链接,它会打开浏览器(默认的) 这是之前它接近出现几秒钟之内。并且没有文件被下载。

下面是我的code, 感谢您的帮助。

 进口android.app.Activity;
进口android.content.Intent;
进口android.net.Uri;
进口android.os.Bundle;
进口android.webkit.WebView;
进口android.webkit.WebViewClient;
进口android.webkit.WebChromeClient;
进口android.view.Menu;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.webkit.DownloadListener;
进口android.widget.Button;
进口android.widget.TextView;

公共类主要扩展活动{
的WebView的WebView;
按钮bt_search;
TextView的txt_search;
@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    的WebView =(web视图)findViewById(R.id.webView);
    webview.setWebChromeClient(新WebChromeClient());
    webview.getSettings()setJavaScriptEnabled(真)。
    webview.setDownloadListener(新DownloadListener(){
        公共无效onDownloadStart(URL字符串,字符串的userAgent,
            字符串contentDisposition,字符串MIMETYPE,
            长CONTENTLENGTH){
          意图I =新的意图(Intent.ACTION_VIEW);
          i.setData(Uri.parse(URL));
          startActivity(ⅰ);
        }
    });
    txt_search =(TextView中)findViewById(R.id.song);
    webview.loadUrl(http://www.google.com);
    bt_search =(按钮)findViewById(R.id.findit);
    bt_search.setOnClickListener(新OnClickListener(){
        公共无效的onClick(视图v){
            。字符串关键字= txt_search.getText()的toString()修剪();
            如果(!keyword.equals()){
                webview.loadUrl(MP3网站+关键字+。html的);
     }
    }
});
}

@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
    //充气菜单;这增加了项目操作栏,如果它是present。
    。getMenuInflater()膨胀(R.menu.main,菜单);
    返回true;
}

    }
 

解决方案

实现一个 WebViewClient 与你的WebView使用。在这里面,重写<一href="https://developer.android.com/reference/android/webkit/WebViewClient.html#shouldOverrideUrlLoading%28android.webkit.WebView,%20java.lang.String%29">shouldOverrideUrlLoading方法,你应该检查,如果它是一个MP3文件,然后通过该网址到下载管理或任何你正在使用的实际下载文件。 这里有一个大概的了解:

  //这将处理下载。它需要姜饼,虽然
    最终的下载管理器管理器=(下载管理器)getSystemService(Context.DOWNLOAD_SERVICE);

    //这是下载的文件将被写入,使用包名称不是必需的
    //但它的沟通谁拥有该目录的好办法
    最终文件destinationDir =新的文件(Environment.getExternalStorageDirectory(),getPackageName());
    如果(!destinationDir.exists()){
        destinationDir.mkdir(); //不要忘了做目录,如果它不存在
    }
    webView.setWebViewClient(新WebViewClient(){
        @覆盖
        公共布尔shouldOverrideUrlLoading(web视图查看,字符串URL){
            布尔shouldOverride = FALSE;
            //我们只希望来处理MP3文件的请求,一切的web视图
            //可以处理正常
            如果(url.endsWith(。MP3)){
                shouldOverride = TRUE;
                乌里源= Uri.parse(URL);

                //创建一个新的请求指向MP3网址
                DownloadManager.Request请求=新DownloadManager.Request(源);
                //使用相同的文件名的目标
                文件destinationFile =新的文件(destinationDir,source.getLastPathSegment());
                request.setDestinationUri(Uri.fromFile(destinationFile));
                //添加到经理
                manager.enqueue(要求);
            }
            返回shouldOverride;
        }
    });
 

I want to download the file(such as .mp3) from the website by using webview but the problem is Whenever I tap on the link, It will open the browser(Default one) Which is appear for a sec before It close. and no file were downloaded.

Here's my code, Thanks for any help.

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.DownloadListener;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity {
WebView webview;
Button bt_search;
TextView txt_search;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    webview = (WebView) findViewById(R.id.webView);
    webview.setWebChromeClient(new WebChromeClient());
    webview.getSettings().setJavaScriptEnabled(true);
    webview.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);
        }
    });
    txt_search = (TextView) findViewById(R.id.song);
    webview.loadUrl("http://www.google.com");
    bt_search = (Button) findViewById(R.id.findit);
    bt_search.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            String keyword = txt_search.getText().toString().trim();
            if (!keyword.equals("")) {
                webview.loadUrl("MP3 Sites" + keyword + ".html");
     }
    }
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

    }

解决方案

Implement a WebViewClient to use with your WebView. In it, override the shouldOverrideUrlLoading method, where you should check if it's an mp3 file, and then pass that URL to the DownloadManager or whatever you're using to actually download the file. Here's a rough idea:

    // This will handle downloading. It requires Gingerbread, though
    final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

    // This is where downloaded files will be written, using the package name isn't required
    // but it's a good way to communicate who owns the directory
    final File destinationDir = new File (Environment.getExternalStorageDirectory(), getPackageName());
    if (!destinationDir.exists()) {
        destinationDir.mkdir(); // Don't forget to make the directory if it's not there
    }
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading (WebView view, String url) {
            boolean shouldOverride = false;
            // We only want to handle requests for mp3 files, everything else the webview
            // can handle normally
            if (url.endsWith(".mp3")) {
                shouldOverride = true;
                Uri source = Uri.parse(url);

                // Make a new request pointing to the mp3 url
                DownloadManager.Request request = new DownloadManager.Request(source);
                // Use the same file name for the destination
                File destinationFile = new File (destinationDir, source.getLastPathSegment());
                request.setDestinationUri(Uri.fromFile(destinationFile));
                // Add it to the manager
                manager.enqueue(request);
            }
            return shouldOverride;
        }
    });

这篇关于我怎样才能下载使用web视图文件? (已搜索的答案,但这种情况下是奇怪)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆