我想使用 webview 从网站下载文件(例如 .mp3),但问题是每当我点击链接时,它都会打开浏览器(默认浏览器),它会在关闭之前出现一秒钟。并且没有下载文件。
这是我的代码,
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;
}
}