本帖最后由 世事繁华皆成空 于 2016-1-6 16:13 编辑
采用Material Dialog设计,样式还是很美观的,为了不影响使用,在点击下载后自动在通知栏进行下载,下载完成后由用户手动去点击通知栏进行安装
云端配置
关键代码:
[Java] 纯文本查看 复制代码 CheckUpdate checkUpdate = new CheckUpdate(this); //实例化自动更新类
checkUpdate.startCheck();
[Java] 纯文本查看 复制代码 public void startCheck() {
new Thread(new Runnable() {
@Override
public void run() {
//4.0+网络请求需要在子线程中完成
URL url;
InputStream is;
HttpURLConnection conn = null;
try {
url = new URL(Constant.APK_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
is = conn.getInputStream(); //网络请求
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
LogUtils.e(sb);
br.close();
is.close();
Message msg = new Message();
msg.what = 0;
msg.obj = sb.toString();
mhandler.sendMessage(msg); //将获取到的数据直接发消息给hanlder去处理
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}).start();
}
hanlder中直接对数据进行解析
[Java] 纯文本查看 复制代码 switch (msg.what) {
case 0:
try {
JSONObject js = new JSONObject(msg.obj.toString());
int version = js.getInt("version");
String intro = js.getString("introduction");
String url = js.getString("url");
compareVersion(version, intro, url);
} catch (JSONException e) {
e.printStackTrace();
}
获取当前APK版本号,这里使用的是versioncode,个人觉得比较方便,当云端版本大于当前版本时,则提示更新
[Java] 纯文本查看 复制代码 private void compareVersion(int newVersion, String intro, final String url) {
int versionCode = getVerCode(mcontext);
LogUtils.e(versionCode);
LogUtils.e(intro);
LogUtils.e(url);
if (newVersion > versionCode) {
new MaterialDialog.Builder(mcontext)
.title("发现更新")
.content(intro)
.positiveText("立即更新")
.negativeText("退出").onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
Intent intent = new Intent(mcontext, DownloadService.class);
intent.putExtra("url", url);
mcontext.startService(intent);
}
})
.show();
} else {
return;
}
}
private int getVerCode(Context ctx) {
int currentVersionCode = 0;
PackageManager manager = ctx.getPackageManager();
try {
PackageInfo info = manager.getPackageInfo(ctx.getPackageName(), 0);
currentVersionCode = info.versionCode; // 版本号
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return currentVersionCode;
}
Demo源码:
https://github.com/Qrilee/AutoCheckUpdate欢迎star
|