Android 自动检测更新,自动下载apk更新版本

注意华为手机需要先上架华为应用市场才可以自动更新apk。其他手机可能也需要先上架

 

关于安卓8.0不显示下载通知问题:https://blog.csdn.net/meixi_android/article/details/83379335

适配安卓10.0关于安卓8.0不能自动安装问题:https://blog.csdn.net/meixi_android/article/details/83584308

主要下载service

 

public class UpdateAppService extends Service {// 标题private int titleId;//版本
//    public static final String APK_VERSION="APK_VERSION";public static final String APK_UIL="APK_UIL";// 文件存储private File updateDir = null;private File updateFile = null;// 通知栏private NotificationManager updateNotificationManager = null;private Notification updateNotification = null;private String strAppUrl;@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stub// 获取传值titleId = intent.getIntExtra("titleId", 0);
//        String strVersion=intent.getStringExtra(APK_VERSION);strAppUrl = intent.getStringExtra(APK_UIL);
//        strAppUrl = MyShareUtil.getSharedString(R.string.APP_UPDATE_URL);// 创建文件if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {updateDir = new File(Environment.getExternalStorageDirectory(), "data/com.tianxin.mapclient.liteapp");updateFile = new File(updateDir.getPath(), getResources().getString(titleId)  +"_V"+".apk");Log.i("lgq","file======"+updateFile);}this.updateNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);this.updateNotification = new Notification();this.updateNotification.flags = Notification.FLAG_AUTO_CANCEL;new Thread(new UpdateRunner()).start();return super.onStartCommand(intent, flags, startId);}private Handler updateHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 1:// 自动安装新版本Log.e("自动安装新版本", updateFile.getName());updateNotificationManager.cancel(0);Intent installIntent = new Intent();installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);installIntent.setAction(Intent.ACTION_VIEW);installIntent.setDataAndType(Uri.fromFile(updateFile), "application/vnd.android.package-archive");startActivity(installIntent);// 停止服务stopSelf();break;case 0:// 下载失败
//                    Notification.Builder builder = new Notification.Builder(this);//新建Notification.Builder对象
//                    PendingIntent  tintent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
//                    builder.setContentTitle("开始下载");
//                    builder.setContentText( "圆心部落  0%");
//                    builder.setSmallIcon(R.mipmap.app);
//                    builder.setContentIntent(tintent);//执行intent
//                    updateNotification = builder.getNotification();//将builder对象转换为普通的notification
//                    updateNotification.setLatestEventInfo(UpdateAppService.this, getApplicationContext().getResources().getString(R.string.app_name), "下载失败", null);
//                    updateNotificationManager.notify(0, updateNotification);stopSelf();break;default:stopSelf();}}};class UpdateRunner implements Runnable {Message message = updateHandler.obtainMessage();@Overridepublic void run() {// TODO Auto-generated method stubmessage.what = 1;try {if (!updateDir.exists()) {updateDir.mkdirs();}if (!updateFile.exists()) {updateFile.createNewFile();}Log.i("lgq下载地址", strAppUrl);long downloadSize = downloadUpdateFile(strAppUrl, updateFile);if (downloadSize > 0) {// 下载成功updateHandler.sendMessage(message);}} catch (Exception ex) {ex.printStackTrace();message.what = 0;// 下载失败updateHandler.sendMessage(message);}}}public long downloadUpdateFile(String downloadUrl, File saveFile)throws Exception {int downloadCount = 0;int currentSize = 0;long totalSize = 0;int updateTotalSize = 0;PendingIntent Pendingintent = PendingIntent.getActivity(UpdateAppService.this, 0, new Intent(Intent.ACTION_VIEW), 0);HttpURLConnection httpConnection = null;InputStream is = null;FileOutputStream fos = null;try {URL url = new URL(downloadUrl);
//            URL url = new URL("http://image.baidu.com/search/detail?ct=503316480&z=0&tn=baiduimagedetail&ipn=d&word=%E7%BD%91%E9%99%85%E9%A3%9E%E4%BE%A0%E7%9A%84%E4%BD%9C%E5%93%81&step_word=&ie=utf-8&in=&cl=undefined&lm=undefined&st=undefined&cs=97365977,1969139888&os=&simid=&pn=0&rn=1&di=0&fr=&fmq=1527155755045_R&fm=&ic=undefined&s=undefined&se=undefined&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=undefined&bdtype=-1&spn=0&pi=49125372204&gsm=0&objurl=http%3A%2F%2Fe.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F500fd9f9d72a6059099ccd5a2334349b023bbae5.jpg&rpstart=0&rpnum=0&adpicid=0&catename=%E9%A3%8E%E5%85%89");httpConnection = (HttpURLConnection) url.openConnection();httpConnection.setRequestProperty("User-Agent", "PacificHttpClient");if (currentSize > 0) {httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-");}httpConnection.setConnectTimeout(10000);httpConnection.setReadTimeout(20000);updateTotalSize = httpConnection.getContentLength();if (httpConnection.getResponseCode() == 404) {throw new Exception("fail!");}is = httpConnection.getInputStream();fos = new FileOutputStream(saveFile, false);byte buffer[] = new byte[4096];int readsize = 0;int persent = 0;while ((readsize = is.read(buffer)) > 0) {fos.write(buffer, 0, readsize);totalSize += readsize;persent = (int) totalSize * 100 / updateTotalSize;if ((downloadCount == 0) || persent - 1 > downloadCount) {Notification.Builder builder = new Notification.Builder(this);//新建Notification.Builder对象PendingIntent Pendingintentt = PendingIntent.getActivity(UpdateAppService.this, 0, new Intent(Intent.ACTION_VIEW), 0);builder.setContentTitle("开始下载");builder.setContentText( "正在下载"+ persent + "%");builder.setSmallIcon(R.mipmap.ic_launcher);builder.setContentIntent(Pendingintentt);//执行intentupdateNotification = builder.getNotification();//将builder对象转换为普通的notificationLog.i("lgqq","body=====MyServiceTestActivity====="+persent);
//                    updateNotification.setLatestEventInfo(UpdateAppService.this, "正在下载", persent >= 0 ? persent + "%" :"努力下载中~", null);downloadCount += 1;Log.v("lgq", persent + "%");updateNotificationManager.notify(0, updateNotification);}}} finally {if (httpConnection != null) {httpConnection.disconnect();}if (is != null) {is.close();}if (fos != null) {fos.close();}}return totalSize;}}

附:上面 updateNotificationManager.notify(0, updateNotification);,可不用。

使用进度条显示加载进度: https://blog.csdn.net/meixi_android/article/details/82456945

 

配置service

 

 

<!-- 自动下载APP -->
<service android:name="com.tianxin.mapclient.liteapp.UpdateAppService" />

 

 

 

查看是否更新版本

 

private void getwebvison() {String url = Url.oneupdversion;//云版本控制链接RequestParams params = new RequestParams();AsyncHttpClient client = new AsyncHttpClient();client.get(url, params, new TextHttpResponseHandler() {@Overridepublic void onFailure(int i, Header[] headers, String s, Throwable throwable) {Toast.makeText(getContext(), "网络连接异常", Toast.LENGTH_SHORT).show();}@Overridepublic void onSuccess(int i, Header[] headers, String s) {try {JSONObject object = new JSONObject(s);contentlg = object.getString("content");//更新内容urllg = object.getString("url");//apk下载链接int versionlg = object.getInt("version");//云版本号int loca = TxApplication.getVersionCode();//本地版本号if (versionlg > loca) {Intent updateIntent = new Intent(getContext(), UpdateAppService.class);updateIntent.putExtra("titleId", R.string.app_name);updateIntent.putExtra(UpdateAppService.APK_UIL, urllg);getActivity().startService(updateIntent);//开始下载}} catch (JSONException e) {e.printStackTrace();}}});}  
//     版本号
public static int getVersionCode() {try {return mTotalContext.getPackageManager().getPackageInfo(mTotalContext.getPackageName(), 0).versionCode;} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();}return 0;
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/415618.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

typescript 接口 interface 的理解

在学习typescript的时候&#xff0c;经常发现别人写了好多接口&#xff08;interface&#xff09;&#xff0c;那问题来了&#xff0c;我们自己写代码&#xff0c;应该在什么情况下写接口才比较合适呢。于是我就找了找资料&#xff0c;整理一下。 接口运行时的影响为 0。TypeS…

前端学习(2619):vue插槽--具名插槽

插槽的最最简单使用&#xff0c;上面已有例子&#xff0c;这里就不写了&#xff0c;接下来看看&#xff0c;插槽其他使用场景 插槽的使用 - 具名插槽 描述&#xff1a;具名插槽其实就是给插槽娶个名字。一个子组件可以放多个插槽&#xff0c;而且可以放在不同的地方&#xff…

程序的灵魂-----算法

一个程序应包括以下两方面的内容&#xff1a; 1、 转载于:https://www.cnblogs.com/lzhn/p/7650689.html

禅道学习笔记

项目部老大&#xff0c;要经常汇总&#xff0c;这时需要查看所有创建的项目和任务&#xff0c;要怎么操作 &#xff1f;&#xff1f;答&#xff1a;可以设置为超级管理员 如何成为超级管理员 禅道系统里面的权限可以通过组织视图里面的权限分组来获得&#xff0c;但其实禅道…

工作119:axios请求封装

/*封装系统需要的post请求 第一个参数传入url地址 第二个传入数据参数*/ export function postAction(url, parameter) {return axios({url: url,method: "post",data: parameter}); } /*封装系统需要的put请求*/ export function putAction(url, parameter) {return…

10-3的随笔继续讲,演绎“圆弧底”

姚振华运作万科a&#xff0c;因为总总原因&#xff0c;姚振华变成了明庄&#xff0c;引起了王石的反抗&#xff0c;强行停牌。去看一下万科A前后的走势&#xff0c;停牌前正是姚振华节节进攻连续封板的时候&#xff0c;停牌六个月期间大盘血崩&#xff0c;所有人都知道姚振华在…

hapi常用插件(持续更新)

catbox 缓存 官方地址 https://hapijs.com/tutorials/caching?langen_US good 进程监控

md5 MD5加密

应用/*** 利用MD5进行加密** param str 待加密的字符串* return 加密后的字符串* throws NoSuchAlgorithmException 没有这种产生消息摘要的算法* throws UnsupportedEncodingException*/public String EncoderByMd5(String str) throws NoSuchAlgorithmException, Unsuppo…

[UVA 10891] Game of Sum

图片加载可能有点慢&#xff0c;请跳过题面先看题解&#xff0c;谢谢 很容易想到这样一个状态&#xff1a;\(dp[l][r]\) 表示&#xff0c;\(l\) 到 \(r\) 这一段区间&#xff0c;双方都使用最优策略时&#xff0c;先手能得到的最大分数 $ $ 那么这个只要怎么求呢&#xff0c;想…

hapi 插件注册 核心代码

准备给自己的hapi框架加上微信开发库这样的插件&#xff0c;需要弄懂hapi如何注册插件、如何给插件传递参数。 1、定义插件 const Pkg require(../package.json) async function register(server, pluginOptions) {console.log(这是一个插件);console.log(这是插件参数);cons…

工作120:富文本组件封装

<template lang"html"><div class"editor"><!--定义的为表头的属性--><div ref"toolbar" class"toolbar"></div><!--定义的为表格的属性--><div ref"editor" class"text"…

mysql 常用命令与备份恢复 整理

常用命令 编辑1:使用SHOW语句找出在服务器上当前存在什么数据库&#xff1a;mysql> SHOW DATABASES;2:2、创建一个数据库MYSQLDATAmysql> CREATE DATABASE MYSQLDATA;3:选择你所创建的数据库mysql> USE MYSQLDATA; (按回车键出现Database changed 时说明操作成功&…

/lib/libcrypto.so“ not found,is 32-bit instead of 64-bit

关于百度导航与百度云推送冲突 只需要加入红色部分 defaultConfig {applicationId "com.tianxin.mient.leapp"minSdkVersion 15targetSdkVersion 27versionCode 19versionName "19.0"// multiDexEnabled truejavaCompileOptions {annotationProces…

运用Zabbix实现内网服务器状态及局域网状况监控(2) —— 环境配置

一、基本要求 Zabbix支持如下操作系统&#xff1a; LinuxIBM AIXFreeBSDNetBSDOpenBSDHP-UXMac OS XSolarisWindows: 2000, Server 2003, XP, Vista, Server 2008, 7, 8, Server 2012 (只能跑 Zabbix agent) 软件需要&#xff1a; 数据库 MySQL&#xff1a; 5.0.3 或者以上&am…

lodash 常用的方法总结(持续更新)

lodash的引入 var _ require(lodash);castArray _.castArray将一个值铸造为数组如果它不是数组类型。 _.castArray(1); // > [1]_.castArray({ a: 1 }); // > [{ a: 1 }]_.castArray(abc); // > [abc]_.castArray(null); // > [null]_.castArray(undefined); //…

WEB技术分类

HTMLXHTML ▪ HTML 5 ▪ CSS ▪ TCP/IPXMLXML ▪ XSL ▪ XSLT ▪ XSL-FO ▪ XPath ▪ XPointer ▪ XLink ▪ DTD ▪ XML Schema ▪ DOM ▪ XForms ▪ SOAP ▪WSDL ▪ RDF ▪ RSS ▪ WAP ▪ Web ServicesWeb脚本JavaScript ▪ HTML DOM ▪ DHTML ▪ VBScript ▪ AJAX ▪ jQuery …

Linux入门——适合初学者

Linux入门——适合初学者学习Linux也有一阵子了&#xff0c;这过程中磕磕撞撞的&#xff0c;遇到了问题&#xff0c;也解决了一些问题&#xff0c;学习的路子是曲折的&#xff0c;想总结点啥的&#xff0c;让刚刚学习Linux的不会望而生畏。 为啥我们要学习Linux 技术的价值不…

Tomcat 配置 login 和 gas

1.首先下载tomcat 2.配置环境变量 export PATH$PATH:/Users/wangchengcheng/Downloads/UtilitySoftWare/Work/ServerTools/apache-tomcat-7.0.82/bin 3.发布login gms 的部署包 4. 修改 server.xml /Users/wangchengcheng/Downloads/UtilitySoftWare/Work/ServerTools/apache-…

1 微信公众号开发 服务器配置 有什么用

启用并设置服务器配置后&#xff0c;用户发给公众号的消息以及开发者需要的事件推送&#xff0c;将被微信转发到该URL中。 换句话说&#xff0c;开发者需要监听这个URL&#xff0c;处理数据&#xff0c;并做出反应。