安卓使用WebView下载文件,安卓实现软件升级功能
由于调用系统默认浏览器下载更新,造成用户体验非常不好,所以决定在webview中直接下载系统更新。然后直接安装。
由于要下载,所以必须用webview,联网权限这里不说了,直接写在manifafest中。
我们经常使用的下载都是调用Android默认浏览器 这样写
1、设置WebView的DownloadListener:
webView.setDownloadListener(new MyWebViewDownLoadListener());
2、实现MyWebViewDownLoadListener这个类,详细能够例如以下这样:
- private class MyWebViewDownLoadListener implements DownloadListener {
- @Override
- public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
- long contentLength) {
- Uri uri = Uri.parse(url);
- Intent intent = new Intent(Intent.ACTION_VIEW, uri);
- startActivity(intent);
- }
- }
为了直接下载,
Sample:
java代码:
public class zwebxiazai extends Activity {
WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.webView=(WebView) this.findViewById(R.id.webview);
this.webView.getSettings().setSupportZoom(false);
this.webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
this.webView.loadUrl("http://a.zntx.cc/");
this.webView.setWebViewClient(new WebViewClientDemo());
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
//实现下载的代码
Uri uri =
Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}
});
}
private class WebViewClientDemo extends WebViewClient {
@Override
// 在WebView中而不是默认浏览器中显示页面
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
main.xml代码:
<?
xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<WebView android:id="@+id/webview" android:layout_width="fill_parent"
android:layout_height="0dip" android:layout_weight="1" />
</LinearLayout>
在AndroidManifest.xml中增加訪问internet的权限:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Sample2 这个比較具体
WebView控制调用对应的WEB页面进行展示。当碰到页面有下载链接的时候,点击上去是一点反应都没有的。
原来是由于WebView默认没有开启文件下载的功能。假设要实现文件下载的功能。须要设置WebView的DownloadListener,通过实现自己的DownloadListener来实现文件的下载。详细操作例如以下:
1、设置WebView的DownloadListener:
webView.setDownloadListener(new MyWebViewDownLoadListener());
2、实现MyWebViewDownLoadListener这个类,详细能够例如以下这样:
- private class MyWebViewDownLoadListener implements DownloadListener{
- @Override
- public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
- long contentLength) {
- Log.i("tag", "url="+url);
- Log.i("tag", "userAgent="+userAgent);
- Log.i("tag", "contentDisposition="+contentDisposition);
- Log.i("tag", "mimetype="+mimetype);
- Log.i("tag", "contentLength="+contentLength);
- Uri uri = Uri.parse(url);
- Intent intent = new Intent(Intent.ACTION_VIEW, uri);
- startActivity(intent);
- }
- }
- private class MyWebViewDownLoadListener implements DownloadListener{
- @Override
- public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
- long contentLength) {
- Log.i("tag", "url="+url);
- Log.i("tag", "userAgent="+userAgent);
- Log.i("tag", "contentDisposition="+contentDisposition);
- Log.i("tag", "mimetype="+mimetype);
- Log.i("tag", "contentLength="+contentLength);
- Uri uri = Uri.parse(url);
- Intent intent = new Intent(Intent.ACTION_VIEW, uri);
- startActivity(intent);
- }
- }
这仅仅是调用系统中已经内置的浏览器进行下载,还没有WebView本身进行的文件下载。只是,这也基本上满足我们的应用场景了。
我在项目中的运用
项目要求这样:
1,须要使用WebView载入一个网页。
2。网页中有文件下载的链接,点击后须要下载文件到SDcard;
3。然后自己主动打开文件;
以下是详细解决的方法
第一步。对WebView进行一系列设置。
- WebView webview=(WebView)layout.findViewById(R.id.webview);
- webview.getSettings().setJavaScriptEnabled(true);
- webview.setWebChromeClient(new MyWebChromeClient());
- webview.requestFocus();
- // webview.loadUrl("file:///android_asset/risktest.html");
- webview.loadUrl(jcrs_sub.get(position).addr);
- // 设置web视图client
- webview.setWebViewClient(new MyWebViewClient());
- webview.setDownloadListener(new MyWebViewDownLoadListener());
- //内部类
- public class MyWebViewClient extends WebViewClient {
- // 假设页面中链接,假设希望点击链接继续在当前browser中响应,
- // 而不是新开Android的系统browser中响应该链接,必须覆盖 webview的WebViewClient对象。
- public boolean shouldOverviewUrlLoading(WebView view, String url) {
- L.i("shouldOverviewUrlLoading");
- view.loadUrl(url);
- return true;
- }
- public void onPageStarted(WebView view, String url, Bitmap favicon) {
- L.i("onPageStarted");
- showProgress();
- }
- public void onPageFinished(WebView view, String url) {
- L.i("onPageFinished");
- closeProgress();
- }
- public void onReceivedError(WebView view, int errorCode,
- String description, String failingUrl) {
- L.i("onReceivedError");
- closeProgress();
- }
- }
- // 假设不做不论什么处理,浏览网页,点击系统“Back”键,整个Browser会调用finish()而结束自身。
- // 假设希望浏览的网 页回退而不是推出浏览器,须要在当前Activity中处理并消费掉该Back事件。
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- // if((keyCode==KeyEvent.KEYCODE_BACK)&&webview.canGoBack()){
- // webview.goBack();
- // return true;
- // }
- return false;
- }
- WebView webview=(WebView)layout.findViewById(R.id.webview);
- webview.getSettings().setJavaScriptEnabled(true);
- webview.setWebChromeClient(new MyWebChromeClient());
- webview.requestFocus();
- // webview.loadUrl("file:///android_asset/risktest.html");
- webview.loadUrl(jcrs_sub.get(position).addr);
- // 设置web视图client
- webview.setWebViewClient(new MyWebViewClient());
- webview.setDownloadListener(new MyWebViewDownLoadListener());
- //内部类
- public class MyWebViewClient extends WebViewClient {
- // 假设页面中链接,假设希望点击链接继续在当前browser中响应。
- // 而不是新开Android的系统browser中响应该链接。必须覆盖 webview的WebViewClient对象。
- public boolean shouldOverviewUrlLoading(WebView view, String url) {
- L.i("shouldOverviewUrlLoading");
- view.loadUrl(url);
- return true;
- }
- public void onPageStarted(WebView view, String url, Bitmap favicon) {
- L.i("onPageStarted");
- showProgress();
- }
- public void onPageFinished(WebView view, String url) {
- L.i("onPageFinished");
- closeProgress();
- }
- public void onReceivedError(WebView view, int errorCode,
- String description, String failingUrl) {
- L.i("onReceivedError");
- closeProgress();
- }
- }
- // 假设不做不论什么处理,浏览网页,点击系统“Back”键,整个Browser会调用finish()而结束自身。
- // 假设希望浏览的网 页回退而不是推出浏览器,须要在当前Activity中处理并消费掉该Back事件。
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- // if((keyCode==KeyEvent.KEYCODE_BACK)&&webview.canGoBack()){
- // webview.goBack();
- // return true;
- // }
- return false;
- }
第二步。起线程開始下载文件。
- //内部类
- private class MyWebViewDownLoadListener implements DownloadListener {
- @Override
- public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
- long contentLength) {
- if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
- Toast t=Toast.makeText(mContext, "须要SD卡。", Toast.LENGTH_LONG);
- t.setGravity(Gravity.CENTER, 0, 0);
- t.show();
- return;
- }
- DownloaderTask task=new DownloaderTask();
- task.execute(url);
- }
- }
- //内部类
- private class DownloaderTask extends AsyncTask<String, Void, String> {
- public DownloaderTask() {
- }
- @Override
- protected String doInBackground(String... params) {
- // TODO Auto-generated method stub
- String url=params[0];
- // Log.i("tag", "url="+url);
- String fileName=url.substring(url.lastIndexOf("/")+1);
- fileName=URLDecoder.decode(fileName);
- Log.i("tag", "fileName="+fileName);
- File directory=Environment.getExternalStorageDirectory();
- File file=new File(directory,fileName);
- if(file.exists()){
- Log.i("tag", "The file has already exists.");
- return fileName;
- }
- try {
- HttpClient client = new DefaultHttpClient();
- // client.getParams().setIntParameter("http.socket.timeout",3000);//设置超时
- HttpGet get = new HttpGet(url);
- HttpResponse response = client.execute(get);
- if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
- HttpEntity entity = response.getEntity();
- InputStream input = entity.getContent();
- writeToSDCard(fileName,input);
- input.close();
- // entity.consumeContent();
- return fileName;
- }else{
- return null;
- }
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- @Override
- protected void onCancelled() {
- // TODO Auto-generated method stub
- super.onCancelled();
- }
- @Override
- protected void onPostExecute(String result) {
- // TODO Auto-generated method stub
- super.onPostExecute(result);
- closeProgressDialog();
- if(result==null){
- Toast t=Toast.makeText(mContext, "连接错误!
请稍后再试!
", Toast.LENGTH_LONG);
- t.setGravity(Gravity.CENTER, 0, 0);
- t.show();
- return;
- }
- Toast t=Toast.makeText(mContext, "已保存到SD卡。", Toast.LENGTH_LONG);
- t.setGravity(Gravity.CENTER, 0, 0);
- t.show();
- File directory=Environment.getExternalStorageDirectory();
- File file=new File(directory,result);
- Log.i("tag", "Path="+file.getAbsolutePath());
- Intent intent = getFileIntent(file);
- startActivity(intent);
- }
- @Override
- protected void onPreExecute() {
- // TODO Auto-generated method stub
- super.onPreExecute();
- showProgressDialog();
- }
- @Override
- protected void onProgressUpdate(Void... values) {
- // TODO Auto-generated method stub
- super.onProgressUpdate(values);
- }
- }
- //内部类
- private class MyWebViewDownLoadListener implements DownloadListener {
- @Override
- public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
- long contentLength) {
- if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
- Toast t=Toast.makeText(mContext, "须要SD卡。", Toast.LENGTH_LONG);
- t.setGravity(Gravity.CENTER, 0, 0);
- t.show();
- return;
- }
- DownloaderTask task=new DownloaderTask();
- task.execute(url);
- }
- }
- //内部类
- private class DownloaderTask extends AsyncTask<String, Void, String> {
- public DownloaderTask() {
- }
- @Override
- protected String doInBackground(String... params) {
- // TODO Auto-generated method stub
- String url=params[0];
- // Log.i("tag", "url="+url);
- String fileName=url.substring(url.lastIndexOf("/")+1);
- fileName=URLDecoder.decode(fileName);
- Log.i("tag", "fileName="+fileName);
- File directory=Environment.getExternalStorageDirectory();
- File file=new File(directory,fileName);
- if(file.exists()){
- Log.i("tag", "The file has already exists.");
- return fileName;
- }
- try {
- HttpClient client = new DefaultHttpClient();
- // client.getParams().setIntParameter("http.socket.timeout",3000);//设置超时
- HttpGet get = new HttpGet(url);
- HttpResponse response = client.execute(get);
- if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
- HttpEntity entity = response.getEntity();
- InputStream input = entity.getContent();
- writeToSDCard(fileName,input);
- input.close();
- // entity.consumeContent();
- return fileName;
- }else{
- return null;
- }
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- @Override
- protected void onCancelled() {
- // TODO Auto-generated method stub
- super.onCancelled();
- }
- @Override
- protected void onPostExecute(String result) {
- // TODO Auto-generated method stub
- super.onPostExecute(result);
- closeProgressDialog();
- if(result==null){
- Toast t=Toast.makeText(mContext, "连接错误。请稍后再试!", Toast.LENGTH_LONG);
- t.setGravity(Gravity.CENTER, 0, 0);
- t.show();
- return;
- }
- Toast t=Toast.makeText(mContext, "已保存到SD卡。
", Toast.LENGTH_LONG);
- t.setGravity(Gravity.CENTER, 0, 0);
- t.show();
- File directory=Environment.getExternalStorageDirectory();
- File file=new File(directory,result);
- Log.i("tag", "Path="+file.getAbsolutePath());
- Intent intent = getFileIntent(file);
- startActivity(intent);
- }
- @Override
- protected void onPreExecute() {
- // TODO Auto-generated method stub
- super.onPreExecute();
- showProgressDialog();
- }
- @Override
- protected void onProgressUpdate(Void... values) {
- // TODO Auto-generated method stub
- super.onProgressUpdate(values);
- }
- }
第三步,实现一些工具方法。
- private ProgressDialog mDialog;
- private void showProgressDialog(){
- if(mDialog==null){
- mDialog = new ProgressDialog(mContext);
- mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条
- mDialog.setMessage("正在载入 ,请等待...");
- mDialog.setIndeterminate(false);//设置进度条是否为不明白
- mDialog.setCancelable(true);//设置进度条能否够按退回键取消
- mDialog.setCanceledOnTouchOutside(false);
- mDialog.setOnDismissListener(new OnDismissListener() {
- @Override
- public void onDismiss(DialogInterface dialog) {
- // TODO Auto-generated method stub
- mDialog=null;
- }
- });
- mDialog.show();
- }
- }
- private void closeProgressDialog(){
- if(mDialog!=null){
- mDialog.dismiss();
- mDialog=null;
- }
- }
- public Intent getFileIntent(File file){
- // Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
- Uri uri = Uri.fromFile(file);
- String type = getMIMEType(file);
- Log.i("tag", "type="+type);
- Intent intent = new Intent("android.intent.action.VIEW");
- intent.addCategory("android.intent.category.DEFAULT");
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent.setDataAndType(uri, type);
- return intent;
- }
- public void writeToSDCard(String fileName,InputStream input){
- if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
- File directory=Environment.getExternalStorageDirectory();
- File file=new File(directory,fileName);
- // if(file.exists()){
- // Log.i("tag", "The file has already exists.");
- // return;
- // }
- try {
- FileOutputStream fos = new FileOutputStream(file);
- byte[] b = new byte[2048];
- int j = 0;
- while ((j = input.read(b)) != -1) {
- fos.write(b, 0, j);
- }
- fos.flush();
- fos.close();
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }else{
- Log.i("tag", "NO SDCard.");
- }
- }
- private String getMIMEType(File f){
- String type="";
- String fName=f.getName();
- /* 取得扩展名 */
- String end=fName.substring(fName.lastIndexOf(".")+1,fName.length()).toLowerCase();
- /* 依扩展名的类型决定MimeType */
- if(end.equals("pdf")){
- type = "application/pdf";//
- }
- else if(end.equals("m4a")||end.equals("mp3")||end.equals("mid")||
- end.equals("xmf")||end.equals("ogg")||end.equals("wav")){
- type = "audio/*";
- }
- else if(end.equals("3gp")||end.equals("mp4")){
- type = "video/*";
- }
- else if(end.equals("jpg")||end.equals("gif")||end.equals("png")||
- end.equals("jpeg")||end.equals("bmp")){
- type = "image/*";
- }
- else if(end.equals("apk")){
- /* android.permission.INSTALL_PACKAGES */
- type = "application/vnd.android.package-archive";
- }
- // else if(end.equals("pptx")||end.equals("ppt")){
- // type = "application/vnd.ms-powerpoint";
- // }else if(end.equals("docx")||end.equals("doc")){
- // type = "application/vnd.ms-word";
- // }else if(end.equals("xlsx")||end.equals("xls")){
- // type = "application/vnd.ms-excel";
- // }
- else{
- // /*假设无法直接打开,就跳出软件列表给用户选择 */
- type="*/*";
- }
- return type;
- }
安卓使用WebView下载文件,安卓实现软件升级功能的更多相关文章
- 转:Http下载文件类 支技断点续传功能
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net ...
- Linux wget 命令下载文件
wget是Linux系统中用来下载文件的工具,其功能还是比较多的,能够下载单个文件,也可以分段下载,下面小编将针对wget命令的用法给大家做个实例介绍. 实例1 :下载单个文件 # wget http ...
- adb导出安卓 把手机内存文件导入到电脑里 adb安装软件
记得先找对路劲adb shellls 最上面的ls: ./ 打头的没有权限.而下面的这些acct sdcard等 都有权限. 然后cd sdcardls 看下目录,发现gxm文件夹在sdcard下面. ...
- WebApp:如何让安卓的webview缓存webapp的html、js和图片等资源
一.开发环境 客户端:安卓+webview(vuejs) 服务器端:tomcat 8.0 二.问题 使用安卓原生+web(基于webpack+vuejs)的方式开发了一个安卓应 ...
- 如何解决安卓SDK无法下载Package的问题
转载自:http://jingyan.baidu.com/article/8275fc86dbe84046a03cf69d.html 有些用户在安装好Android SDK后,打开Android SD ...
- S如何解决安卓DK无法下载Package问题
安装一些用户Android SDK后.打开Android SDK Manager下载API当总是显示"Done loading packages"却迟迟不能前进.自己也出现了这样的 ...
- 成都优步uber司机客户端下载-支持安卓、IOS系统、优步司机端Uberpartner
国外打车软件优步乘客端大家在手机应用商店里都可以下载到,但是优步司机的App却不好找下载地址:这就跟滴滴打车一样,滴滴的乘客端是滴滴打车,而司机端是滴滴专车,司机版本在应用商店里都找不到,原因不清楚. ...
- 如何解决安卓SDK无法下载Package的问题 分类: H1_ANDROID 2013-09-09 10:26 1199人阅读 评论(0) 收藏
转载自:http://jingyan.baidu.com/article/8275fc86dbe84046a03cf69d.html 有些用户在安装好Android SDK后,打开Android SD ...
- 【资源下载】安卓VS鸿蒙第三方件切换宝典 V1.0
下载<安卓VS鸿蒙第三方件切换宝典> 由于字数较多,本文仅展示部分,查看完整版请点击上方下载 众所周知,安卓应用开发经过这么多年的发展相对成熟和稳定,鸿蒙OS作为后来者兼容一个成熟的开发体 ...
随机推荐
- Python IO编程-组织文件
对于日常中遇到的批量任务,有些可以通过请求python完成自动化,我非常渴望拥有这些能力,在去年学习了python读写文件之后,我马上迫不及待的开始学习‘组织文件’,经过学习,我发现python组织文 ...
- ECNUOJ 2857 编辑距离
编辑距离 Time Limit:5000MS Memory Limit:65536KBTotal Submit:314 Accepted:128 Description 有两个字符串(仅有英文小写字 ...
- WebKit载入流程 - 概述
之前写了几篇载入流程的说明,是从下向上看,有点仅仅见树木不见森林的感觉.经过近期一段时间的学习,有了能加以概括抽象的方法. WebKit载入流程和页面组成是直接相关的,页面就是WebKit要载入的对象 ...
- iOS经常使用设计模式——工厂方法(简单工厂模式,工厂方法模式, 抽象工厂模式)
1. 简单工厂模式 怎样理解简单工厂,工厂方法. 抽象工厂三种设计模式? 简单工厂的生活场景.卖早点的小摊贩.他给你提供包子,馒头,地沟油烙的煎饼等,小贩是一个工厂.它生产包子,馒头,地沟油烙的煎饼. ...
- 影响FPGA设计中时钟因素的探讨。。。转
http://www.fpga.com.cn/advance/skill/speed.htm http://www.fpga.com.cn/advance/skill/design_skill3.ht ...
- How to search Installed Updates
Windows本身的控制面板中自带的搜索,无法根据补丁编号进行搜索 可以将补丁信息导出到文本,再用文本编辑器进行查找 https://www.concurrency.com/blog/w/search ...
- LSTM入门学习——结合《LSTM模型》文章看
摘自:https://zybuluo.com/hanbingtao/note/581764 写得非常好 见原文 长短时记忆网络的思路比较简单.原始RNN的隐藏层只有一个状态,即h,它对于短期的输入非常 ...
- assert 的理解
assert 可以实现如下功能: 保证参数之间的大小等约束关系: 函数执行过程中得到的中间结果是否符合预期: def gen_batch(batch_size, skip_window, num_sk ...
- Google Summer of Code 2017 经验谈
Google Summer of Code (GSoC) 2018 又要开始了. 如果想实现你心中的开源梦想, 用代码让世界变得更美好. 参加GSoC可能是你进入开源的世界最好途径. GSoC是什么 ...
- AnkhSvn介绍 插件
转载:http://www.cnblogs.com/lyhabc/articles/2483011.html AnkhSVN是一款在VS中管理Subversion的插件,您可以在VS中轻松的提交.更新 ...
