思路

在app启动时候去请求服务器上的app版本号,看是否大于本地版本号,本地版本号使用 SharedPreferences 方式保,当服务器版本号大于本地版本号就进行下载更新操作。

1、UpdateManager

package com.rfid.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; import org.json.JSONException;
import org.json.JSONObject; import com.UHF.scanlable.R;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response; import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast; public class UpdateManager { OkHttpClient okHttpClient = new OkHttpClient();
private Context mContext;
private SharedPreferences preferences;
private int version;
private String apkName;
private String apkUrl; private static final String URL ="http://localhost:8080/apkUpdateVersion/updateVersion.json";
private static final String savePath = "/sdcard/updateAPK/";
private String saveFileName = savePath; private ProgressBar mProgress;
private static final int DOWNLOADING = 1;
private static final int DOWNLOADED = 2;
private static final int DOWNLOAD_FAILED = 3;
private int progress;
private boolean cancelFlag = false; private String updateDescription = "更新描述";
private boolean forceUpdate = true; private AlertDialog alertDialog1, alertDialog2; public UpdateManager(Context context) {
this.mContext = context;
} public void checkUpdate(){
final int localVersion = getLocalVersion();
Request request = new Request.Builder()
.url(URL).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new com.squareup.okhttp.Callback() { @Override
public void onResponse(Response response) throws IOException { String json = response.body().string();
try {
JSONObject jsonObject = new JSONObject(json);
version = jsonObject.getInt("version");
apkName = jsonObject.getString("apkName");
apkUrl = jsonObject.getString("apkUrl"); new Thread(new Runnable() {
@Override
public void run() {
if(version > localVersion){
showNoticeDialog(version, localVersion);
// Message msg = new Message();
// msg.what = 1;
// mHandler.sendMessage(msg);
} }
}).start();
} catch (JSONException e) {
e.printStackTrace(); }
} @Override
public void onFailure(com.squareup.okhttp.Request request,
IOException ioexception) { }
}); } //获取本地版本
private int getLocalVersion()
{
preferences = mContext.getSharedPreferences(VersionService.VERSION_KEY, mContext.MODE_ENABLE_WRITE_AHEAD_LOGGING | mContext.MODE_MULTI_PROCESS); VersionService verService = new VersionService(preferences);
int version = verService.getVersion(); return version;
} public void showNoticeDialog(double serverVersion,double clientVersion) {
if (serverVersion <= clientVersion)
return;
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle("发现新版本 :" + serverVersion);
dialog.setMessage(updateDescription); dialog.setPositiveButton("现在更新", new OnClickListener() { @Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
showDownloadDialog();
}
}).show(); if(forceUpdate==false){
dialog.setNegativeButton("待会更新", new OnClickListener() { @Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss(); }
}); }
} public void showDownloadDialog(){ AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle("正在更新"); final LayoutInflater inflater = LayoutInflater.from(mContext); View v = inflater.inflate(R.layout.update_progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.update_progressBar);
dialog.setView(v); if(forceUpdate==false){
dialog.setNegativeButton("待会更新", new OnClickListener() { @Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
cancelFlag = false;
}
}); } alertDialog2 = dialog.create();
alertDialog2.setCancelable(false);
alertDialog2.show(); //下载apk
downloadAPK(); } //下载apk
public void downloadAPK(){ new Thread(new Runnable() { @Override
public void run() {
try {
URL url = new URL(apkUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect(); int length = conn.getContentLength();
InputStream is = conn.getInputStream(); File file = new File(savePath);
if(!file.exists()){
file.mkdir();
}
//修改保存apk名称 apk_v1.apk
saveFileName = savePath + apkName+"_V"+ version+".apk";
String apkFile = saveFileName;
File ApkFile = new File(apkFile);
FileOutputStream fos = new FileOutputStream(ApkFile); int count = 0;
byte buf[] = new byte[1024]; do{
int numread = is.read(buf);
count += numread; progress = (int)(((float)count / length) * 100);
mHandler.sendEmptyMessage(DOWNLOADING); if(numread <= 0){
mHandler.sendEmptyMessage(DOWNLOADED);
break;
}
fos.write(buf, 0, numread);
}while(!cancelFlag); fos.close();
is.close(); } catch (Exception e) {
mHandler.sendEmptyMessage(DOWNLOAD_FAILED);
e.printStackTrace();
} }
}).start();
} private Handler mHandler = new Handler(){ @Override
public void handleMessage(Message msg){ switch (msg.what){
case DOWNLOADING:
mProgress.setProgress(progress);
break;
case DOWNLOADED:
if (alertDialog2 != null)
alertDialog2.dismiss();
//安装apk
installAPK();
break;
case DOWNLOAD_FAILED:
Toast.makeText(mContext, "网络断开,请稍候再试", Toast.LENGTH_LONG).show();
break;
default:
break;
}
} }; public void installAPK(){
File apkFile = new File(saveFileName);
if (!apkFile.exists()) {
return;
} Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
mContext.startActivity(intent); //将服务版本保存到客户端
saveSeverVersion();
} public void saveSeverVersion(){
VersionService verService = new VersionService(preferences);
verService.save(version, apkName);
} }

2、VersionService

package com.rfid.util;

import android.content.SharedPreferences;

public class VersionService {

    public final static String VERSION_KEY = "VERSION_KEY";
public final static String APK_NAME = "APK_NAME"; private SharedPreferences preferences; public VersionService(SharedPreferences preferences){
this.preferences = preferences;
} public int getVersion(){
SharedPreferences.Editor editor = preferences.edit();
int version = preferences.getInt(VERSION_KEY,1);
return version;
} public String getApkName(){
SharedPreferences.Editor editor = preferences.edit();
String apkName = preferences.getString(APK_NAME,"UHF_5100.apk");
return apkName;
} public boolean save(int version,String apkName){
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(VERSION_KEY,version);
editor.putString(APK_NAME,apkName);
return editor.commit();
}
}

3、update_progress.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" > <ProgressBar
android:id="@+id/update_progressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal" />
</LinearLayout>

4、MainActivity调用方式

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity); UpdateManager manager = new UpdateManager(MainActivity.this);
// 检查软件更新
manager.checkUpdate();
}

5、eclipse-android 开发工具 下载okhttp jar 包:

链接:https://pan.baidu.com/s/1qF-A93AuZf9weWsWQcyWrw 密码:19re

6、案例下载

http://files.cnblogs.com/coolszy/UpdateSoftDemo.rar

android 更新版本的更多相关文章

  1. [转] Android SDK manager 无法获取更新版本列表

      打开这个网址(LINK)就可以看到adt的详细信息. 或者直接在你的eclipse的Help > Install New Software里面add,地址直接输入 https://dl-ss ...

  2. android 检查软件是否有更新版本

    import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import com.yuxin.m ...

  3. Android 6.0 7.0 8.0 一个简单的app内更新版本-okgo app版本更新

    登陆时splash初始页调用接口检查app版本.如有更新,使用okGo的文件下载,保存到指定位置,调用Android安装apk. <!-- Android 8.0 (Android O)为了针对 ...

  4. android SDK manager 无法获取更新版本列表【转载】

    http://mirrors.neusoft.edu.cn/eclipse/releases/luna/打开这个网址就可以看到adt的详细信息:  http://developer.android.c ...

  5. android SDK manager 无法获取更新版本的解决办法

    http://mirrors.neusoft.edu.cn/eclipse/releases/luna/打开这个网址就可以看到adt的详细信息:  http://developer.android.c ...

  6. Android历史版本Logo

        Android操作系统是一个由Google和开放手持设备联盟共同开发发展的移动设备操作系统,其最早的一个版本Android 1.0 beta发布于2007年11月5日,至今已经发布了多个更新. ...

  7. Android 各个版本WebView

    转载请注明出处   http://blog.csdn.net/typename/ powered by miechal zhao : miechalzhao@gmail.com 前言: 根据Googl ...

  8. 【Android 应用开发】 Android 各种版本简介 ( Support 支持库版本 | Android Studio 版本 | Gradle 版本 | jcenter 库版本 )

    初学者遇到 Android Studio, 导入工程后, 会出现各种奇葩错误, 如果管理好各个插件, gradle, SDK, SDK Tools, 各种官方依赖库 的版本, 会将错误大大的减少; 这 ...

  9. Android各版本特性

    此篇文章可以利用碎片化时间进行消化和了解,针对Android各个版本特性,并没有把所有列出,只是抽出了比较常用重要的特性作为提示,同时在面试中只要牢记重要的几个点即可,其他特性直接查找官方文档即可. ...

随机推荐

  1. Websocket实现Java后台主动推送消息到前台

    写在前面 需求: 项目测试, 缺少用户登录失败给admin推送消息, 想到这个方式, 当用户登录失败时, admin用户会在页面看到咣咣乱弹的alert. 正文 pom.xml <!-- web ...

  2. SQLServer charindex函数, 查 某个字符 或 某个字符串 在 另一个字符串中的位置

    一:charindex()语法 CHARINDEX ( expression1 , expression2 [ , start_location ] ) 解析: expression1 必需 ---要 ...

  3. WebGL学习笔记(二):WebGL坐标系及基础几何概念

    WebGL使用的是正交右手坐标系,且每个方向都有可使用的值的区间,超出该矩形区间的图像不会绘制: x轴最左边为-1,最右边为1: y轴最下边为-1,最上边为1: z轴朝向你的方向最大值为1,远离你的方 ...

  4. Win 10 MSYS2 VS Code 配置 c++ 的编译环境

    博客参考 https://www.cnblogs.com/esllovesn/p/10012653.html 和 https://blog.csdn.net/bat67/article/details ...

  5. Qt 图片缩放参数计算

    缩放图片 void VCImgWidget::wheelEvent(QWheelEvent *event) { ) { // 当滚轮远离使用者时 //ui->textEdit->zoomI ...

  6. 根据 sitemap 的规则[0],当前页面 [pages/index/index] 将被索引

    sitemap 的索引提示是默认开启的,如需要关闭 sitemap 的索引提示,可在小程序项目配置文件 project.config.json 的 setting 中配置字段 checkSiteMap ...

  7. Linux故障排查之CPU占用率过高

    有时候我们可能会遇到CPU一直占用过高的情况.之前我的做法是,直接查找到相关的进程,然后杀死或重启即可.这个方法对于一般的应用问题还不大,但是要是是重要的环境的话,可万万使不得. 如果是重要的环境,那 ...

  8. function的json对象转换字符串与字符串转换为对象的方法

    // json对象转换成字符串var str = JSON.stringify(json, function(key, val) { if (typeof val === 'function') { ...

  9. linux中安装robot环境

    https://www.cnblogs.com/lgqboke/p/8252488.html(文中验证robotframework命令应该为 robot --version) 可能遇到的问题: 1.p ...

  10. 【知识总结】Polya 定理

    我第一次听说 Polya 原理是 NOIP2017 以前,但我觉得太难想着以后再学: NOIP2018 以前我觉得会考这玩意,下定决心学,后来咕了: WC2019 以前我觉得会考这玩意,下定决心学,后 ...