1.添加依赖:
compile 'org.xutils:xutils:3.5.0' compile 'com.google.code.gson:gson:2.8.1' 2.初始化xutilspublic class BaseApplication extends Application {@Override public void onCreate() {super.onCreate();x.Ext.init(this);x.Ext.setDebug(BuildConfig.DEBUG);} }
3.定义一个获取version的工具类:
public class VersionUtils {/** * 获取应用的版本 */ public static int getVersionCode(Context context) {int versionCode = 0;try {PackageManager packageManager = context.getPackageManager();String packageName = context.getPackageName();PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);versionCode = packageInfo.versionCode;} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();}return versionCode;} } 4.Bean类public class MessageBean<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;} }
=====================================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;} }
5.MainActivity 页面代码public class MainActivity extends AppCompatActivity implements View.OnClickListener {private Button check;private String url="http://172.18.47.57/checkversion.php";private static final String TAG = "MainActivity";private ProgressDialog progressDialog;// 文件保存地址 private String targetPath = "";@Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);x.view().inject(this);check= (Button) findViewById(R.id.btn_check_version);//版本更新的监听事件 check.setOnClickListener(this);//设置sdcard的根路径 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);}@Override public void onClick(View v) {//检查版本号 checkVersion();}private void checkVersion() {//获得自己app当前的版本号,用来和服务器的版本进行对比 final int code = VersionUtils.getVersionCode(this);RequestParams params=new RequestParams(url);params.addQueryStringParameter("version",String.valueOf(code));x.http().get(params, new Callback.CommonCallback<String>() {@Override public void onSuccess(String result) {if (result!=null){Log.i(TAG, "onSuccess: " + result);Gson gson = new Gson();Type type = new TypeToken<MessageBean<Version>>() {}.getType();MessageBean<Version> messageBean = gson.fromJson(result, type);if (messageBean.isSuccess()){final Version version = messageBean.getResult();//强制更新 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 if(version.isHasNewVersion()){//选择更新 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) {}@Override public void onCancelled(CancelledException cex) {}@Override public void onFinished() {}});}private void updateVersion(String url) {//下载的app文件名:当前时间.apk 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();}//自动安装app的方法 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);}}});}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());}}