安卓使用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作为后来者兼容一个成熟的开发体 ...
随机推荐
- HDU——T 2818 Building Block
http://acm.hdu.edu.cn/showproblem.php?pid=2818 Time Limit: 2000/1000 MS (Java/Others) Memory Limi ...
- ios学习:swift中实现分享到微博、facebook,twitter等
在swift中打开分享功能原来是如此的简单. 1.首先须要 import Social 2.在分享button事件以下 var controller:SLComposeViewController = ...
- Light OJ 1341 Aladdin and the Flying Carpet
题意:求大于b的a的因数对有几组.例10 2结果为{2,5},12 2结果为{2,6}{3,4}-----不反复 解一:分解质因数+DFS #include <iostream> #in ...
- 128.C++文件操作小结
打开后缀参数 #include <fstream> #include <iostream> using namespace std; //文本读写 //文件写入 void ma ...
- 125.C++输入小结
#include <iostream> #include <iomanip> #include <cstring> #include <cstdlib> ...
- 团队作业——团队项目Alpha版本发布
该作业所属课程 https://edu.cnblogs.com/campus/xnsy/SoftwareEngineeringClass2 作业要求链接 https://edu.cnblogs. ...
- HDU2665 kth number 线段树做法
题意:求区间第k小 思路: 线段树 每个节点上保存 当前区间已经排序好的序列 (归并一下就好了嘛 复杂度 O(l)的) 这样建树的时空复杂度都是 O(nlogn)的 对于 每次询问 二分一个答案 在树 ...
- HDU 5370 Tree Maker
一个显然的结论是,一棵n个结点的二叉树的形态数,是Catalan数第n项.
- spring-cloud-netflix集成的服务
1.Ribbon Ribbon is a client side IPC library that is battle-tested in cloud. It provides the followi ...
- Day2代码
#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #defi ...