1.导包 :Xutils Gson
加权限 : 网络、读写权限 "android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
2.定义一个类 继承
Application,然后初始化x.Ext.init(
this
);
x.Ext.setDebug(BuildConfig.
DEBUG
);然后在MainActivity中,
x.
view
().inject(
this
);
3.定义一个类,写一个用来获取当前应用的版本号的方法,包管理 PackageManager
包名字getPackageName 包信息 PackageInfo
应用的版本 codepackageInfo.versionCode
4.然后写Bean类,数据
5.解析数据Gson,得到
messageBean对象,判断messageBean成功后,是否有更新。如果有更新,在判断是否是强制更新还是选择更新,如果没更新,吐司就行。
6.如果是强制更新,就弹出一个框
AlertDialog
,设置标题为
版本更新,
设置消息为
升级到最新版本
,
设置为不可取消;
如果是选择更新,也弹出一个框
AlertDialog,
设置消息为
是否要升级到最新版本
。
这两个要升级的时候,都需要下载的目录,定义一个
版本更新的方法,设置下载保存路径 params.setSaveFilePath(),用xutils的文件下载,实现
ProgressCallback
接口,重写7个方法,在
onLoading
中,进行设置进度条。成功了就隐藏进度条,并且安装apk。
代码:
BaseApplication:
import android.app.Application; import org.xutils.x; public class BaseApplication extends Application { @Override public void onCreate() { super.onCreate(); x.Ext.init(this); x.Ext.setDebug(BuildConfig.DEBUG); } }VersionUtils:
package com.bawei.liujie.versonupdate; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; public class VersionUtils { /** * 获取当前应用的versionCode */ public static int getVersionCode(Context context) { int versionCode = 0; try { // 包管理 PackageManager packageManager = context.getPackageManager(); // 包名字 String packageName = context.getPackageName(); // 包信息 PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0); // 应用的版本code versionCode = packageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return versionCode; } }Message:
public class Message<T> { private boolean success; private String message; private T result; public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getResult() { return result; } public void setResult(T result) { this.result = result; } }Version: import com.google.gson.annotations.SerializedName; public class Version { @SerializedName("has_new_version") private boolean hasNewVersion; @SerializedName("must_update") private boolean mustUpdate; private String url; public boolean isHasNewVersion() { return hasNewVersion; } public void setHasNewVersion(boolean hasNewVersion) { this.hasNewVersion = hasNewVersion; } public boolean isMustUpdate() { return mustUpdate; } public void setMustUpdate(boolean mustUpdate) { this.mustUpdate = mustUpdate; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }mainactivity中: import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.xutils.common.Callback; import org.xutils.http.RequestParams; import org.xutils.view.annotation.ContentView; import org.xutils.view.annotation.Event; import org.xutils.x; import java.io.File; import java.lang.reflect.Type; @ContentView(R.layout.activity_main) public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private String url = "http://172.18.47.28/checkversion.php"; // 文件保存地址 private String targetPath = ""; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); x.view().inject(this); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File file = Environment.getExternalStorageDirectory(); targetPath = file.getAbsolutePath() + File.separator; } progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); } @Event(R.id.btn_check_version) private void btnClick(View v) { checkVerson(); } /** * 检查版本号 */ private void checkVerson() { int versionCode = VersionUtils.getVersionCode(this); RequestParams params = new RequestParams(url); params.addQueryStringParameter("version", String.valueOf(versionCode)); x.http().get(params, new Callback.CommonCallback<String>() { @Override public void onSuccess(String result) { Log.i("---------", "onSuccess: " + result); Gson gson = new Gson(); Type type = new TypeToken<Message<Version>>() { }.getType(); Message<Version> messageBean = gson.fromJson(result, type); if (messageBean.isSuccess()) { final Version version = messageBean.getResult(); // 有更新 if (version.isHasNewVersion()) { // 强制更新 if (version.isMustUpdate()) { new AlertDialog.Builder(MainActivity.this) .setTitle("版本更新") .setMessage("升级到最新版本") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { updateVersion(version.getUrl()); dialog.dismiss(); } }) // 不可取消 .setCancelable(false) .create().show(); }else{ // 选择更新 new AlertDialog.Builder(MainActivity.this) .setTitle("版本更新") .setMessage("是否要升级到最新版本") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { updateVersion(version.getUrl()); dialog.dismiss(); } }) .setNegativeButton("下次再说", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create().show(); } } else { // 无可用更新 Toast.makeText(MainActivity.this, "当前已经是最新版本", Toast.LENGTH_SHORT).show(); } } } @Override public void onError (Throwable ex,boolean isOnCallback){ Log.i("------------", "onError: " + ex.getMessage()); } @Override public void onCancelled (CancelledException cex){ } @Override public void onFinished () { } }); } /** * 版本更新 */ private void updateVersion(String url) { targetPath = targetPath + System.currentTimeMillis() + ".apk"; RequestParams params = new RequestParams(url); // 设置下载保存路径 params.setSaveFilePath(targetPath); // xutils的文件下载 x.http().get(params, new Callback.ProgressCallback<File>() { @Override public void onSuccess(File result) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } installApk(result); } @Override public void onError(Throwable ex, boolean isOnCallback) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show(); } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } @Override public void onWaiting() { } @Override public void onStarted() { } @Override public void onLoading(long total, long current, boolean isDownloading) { if (isDownloading) { progressDialog.setMessage("正在下载..."); progressDialog.show(); progressDialog.setMax((int) total); progressDialog.setProgress((int) current); } } }); } /** * 安装apk */ private void installApk(File file) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory("android.intent.category.DEFAULT"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); startActivity(intent); android.os.Process.killProcess(android.os.Process.myPid()); } }