我使用WebView创建了一个Android应用程序,但我遇到的唯一问题是文件是在默认浏览器中打开而不是下载。
这是WebActivity代码:
public class WebActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.webView01);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new myWebClient()
{
@Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.imageLoading1).setVisibility(View.GONE);
findViewById(R.id.webView01).setVisibility(View.VISIBLE);
}
});
webView.loadUrl("domain");
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);
}
});
}
public class myWebClient extends WebViewClient
{
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
答案 0 :(得分:0)
浏览器应用程序正在打开,因为它是用于处理Intent
将URL作为其数据的相应应用程序,这是您在DownloadListener
中使用的内容。
如果您不希望浏览器启动,请使用InputStream
中的URL打开DownloadListener
并自行从文件中获取字节。
public void saveUrl(final String filename, final String urlString)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(filename);
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
}
}