闲来无事,写个版本更新的demo
通常app都是在 欢迎界面 做一些初始化或者检查版本的方法
首先呢 是onCreate方法
SharePreferenceUtil sp;
int versionCode = -1; //初始化版本号
Activity activity;
Intent intent;
/**
* 是否需要引导页
*/
boolean isNeedGuide; // 是否需要引导页
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item01);//
activity = this;
try {
versionCode = activity.getPackageManager().getPackageInfo(
this.getPackageName(), 0).versionCode;
initSpu.setCurrentVersionCode(versionCode);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
sp = new SharePreferenceUtil(XieSplashActivity.this, "config_time");
checkStoragePathAndSetBaseApp(); //得到路径
new UpdateTask().execute();//这个方法里面写的有跳转到主界面
}
UpdateTask 是个 异步任务,接下来看下这个方法
class UpdateTask extends AsyncTask<Void, Void, Boolean> {
Handler m_mainHandler;//下载时所用的 更新 dialog
ProgressDialog m_progressDlg; // 下载时用的进度条
String updateContent = "更新内容:\n";
int m_newVerCode; // 最新版的版本号
String m_newVerName; // 最新版的版本名
String downloadURL; // 更新APP的下载地址
int updateType = -1;
File file; // 更新文件
public UpdateTask() {
m_mainHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
m_progressDlg.setProgress(m_progressDlg.getProgress() + msg.arg1);//实时的更新进度条
break;
case 1:
install();//下载完成后安装apk
break;
case 2:
error();//下载出错
break;
}
}
};
//下载用的进度条
m_progressDlg = new ProgressDialog(activity); // new出一个ProgressDIalog
m_progressDlg.setCancelable(false);
m_progressDlg.setCanceledOnTouchOutside(false);
m_progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 设置为水平样式的Dialog
// 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
m_progressDlg.setIndeterminate(false);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Void... params) {
//从服务器获取最新版本号,如果成功返回true,如果失败返回false
return postCheckNewestVersionCommand2Server();
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (aBoolean) {
//如果true 下载更新
doNewVersionUpdate();
} else {
//进入主界面
toMain();
}
}
/**
* 从服务器获取最新版本号,如果成功返回true,如果失败返回false
*
* @return 是否有新版本,true为新版本,false为没有新版本
*/
private Boolean postCheckNewestVersionCommand2Server() {
try {
String deviceId = initSpu.getDeviceId();
if (TextUtils.isEmpty(deviceId)) {
deviceId = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
.getDeviceId();
if (TextUtils.isEmpty(deviceId)) {
deviceId = String.valueOf(System.currentTimeMillis());
}
initSpu.setDeviceId(deviceId);
}
String result = HttpUtils.doPost(activity, Constant.SERVER_CHECK_NEW_VERSION, "&versionCode=" + versionCode);//版本更新检测地址
JSONObject json = JSON.parseObject(result);//这里用的是 fastJson 其实都一样
JSONObject data = json.getJSONObject(Constant.DATA);
updateContent += data.getString("updateContent");//更新内容
m_newVerCode = Integer.parseInt(data.getString("versionCode"));//最新版本号
updateType = Integer.parseInt(data.getString("updateType"));//更新类型。
ACache aCache = ACache.get(getApplicationContext());//用的缓存类
if (!TextUtils.isEmpty(aCache.getAsString(m_newVerCode + "")) && updateType == 0) {
return false;
}
m_newVerName = data.getString("versionName");//新版本名称
downloadURL = data.getString("fileUrl");
return m_newVerCode > versionCode;//如果true 有新版本
} catch (NullPointerException | JSONException e) {
return false;
}
}
/**
* 提示更新新版本
*/
private void doNewVersionUpdate() {
String verName = getVerName();//得到版本名字
String tip = "";
if (!NetUtils.isWiFi(getApplicationContext())) {
tip = "当前不是WiFi状态 ";
}
String str = tip + "当前版本:" + verName
+ "\n发现新版本:" + m_newVerName;//m_newVerName在上面已经得到
if (updateType == 2) {
str += "[强制更新]";
}
str += "\n" + updateContent;
Dialog dialog = new AlertDialog.Builder(activity)
.setTitle("版本更新")
.setMessage(str)
.setCancelable(false)
.setPositiveButton("更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
m_progressDlg.setTitle("正在下载");
m_progressDlg.setMessage("请稍后");
m_progressDlg.show();
downLoad(downloadURL);//开始下载
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (updateType) {
case 0:
ACache.get(getApplicationContext()).put(m_newVerCode + "", m_newVerCode);
toMain();
break;
case 1:
if (null != ACache.get(getApplicationContext()).getAsString(m_newVerCode + "")) {
ACache.get(getApplicationContext()).remove(m_newVerCode + "");
}
toMain();
break;
case 2:
//强制更新
if (null != ACache.get(getApplicationContext()).getAsString(m_newVerCode + "")) {
ACache.get(getApplicationContext()).remove(m_newVerCode + "");
}
finish();
break;
}
}
}).create();
dialog.show();
}
/**
* 下载文件
*
* @param urlStr
*/
private void downLoad(final String urlStr) {
//开启子线程 下载文件
ThreadPoolUtils.execute(new Runnable() {
@Override
public void run() {
String m_appNameStr = urlStr.substring(urlStr.lastIndexOf("/") + 1);//拿到appname字符串
OutputStream output = null;
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
File dic = new File(Environment.getExternalStorageDirectory() + "/Aat");//文件路径
if (!dic.exists()) {
dic.mkdir();
}
file = new File(Environment.getExternalStorageDirectory() + "/Aat"
+ "/" + m_appNameStr); // 得到存储路径,新建一个name为m_appNameStr的文件
if (file.exists()) {
file.delete();
}
file.createNewFile();
InputStream input = conn.getInputStream();
m_progressDlg.setMax(conn.getContentLength());//设置 进度条的最大值
output = new FileOutputStream(file);
//读取大文件
int ch;
byte[] buffer = new byte[1024];
while ((ch = input.read(buffer)) != -1) {
output.write(buffer, 0, ch);
Message msg = Message.obtain();
msg.what = 0;
msg.arg1 = 1024;
m_mainHandler.sendMessage(msg);//更新进度条
}
output.flush();
} catch (IOException e) {
m_mainHandler.sendEmptyMessage(2);
e.printStackTrace();
} finally {
try {
if (null != output) {
output.close();
m_mainHandler.sendEmptyMessage(1);//下载完成后,安装apk
}
} catch (IOException e) {
m_mainHandler.sendEmptyMessage(2);
e.printStackTrace();
}
}
}
});
}
/**
* 安装apk
*/
private void install() {
m_mainHandler.post(new Runnable() {
@Override
public void run() {
m_progressDlg.cancel(); // 更新UI,隐藏progressDialog
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive"); // 跳转APP安装
activity.startActivity(intent);
finish();
}
});
}
private void error() {
m_mainHandler.post(new Runnable() {
public void run() {
m_progressDlg.cancel(); // 更新UI,隐藏progressDialog
Toast.makeText(activity, "更新失败", Toast.LENGTH_SHORT).show();
}
});
}
}