手机App版本更新(强制更新/选择更新)

news/2024/11/24 11:47:29/

1.添加依赖:

compile 'org.xutils:xutils:3.5.0'
compile 'com.google.code.gson:gson:2.8.1'

2.初始化xutils
public 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());}}





http://www.ppmy.cn/news/773861.html

相关文章

乐视揭秘Android5.0手机APP安装失败真相

Android5 0正在成为手机行业的新趋势&#xff0c;越来越多的手机厂商开始推出Android5 0系统的新一代手机。 Android5.0正在成为手机行业的新趋势&#xff0c;越来越多的手机厂商开始推出Android5.0系统的新一代手机。乐视更是一口气推出三大旗舰手机&#xff0c;三款手机搭载的…

乐视android版本怎么升级,乐视网android手机客户端升级

3月31日消息&#xff0c;乐视网android手机客户端V2.0版——“乐视影视”正式发布&#xff0c;据乐视网运营副总裁高飞介绍&#xff0c;“V2.0版是早期发布的乐视网android手机客户端V1.5版的升级版本&#xff0c;基于乐视网第一影视剧库的内容&#xff0c;在用户体验方面做了全…

nginx四层转发应用

默认使用yum安装的nginx是没有额外安装的动态模块的&#xff0c;需要自己额外安装 ls /usr/lib64/nginx/modules/ 若是不安装stream模块&#xff0c;直接在nginx的配置文件中调用stream模块&#xff0c;重载配置文件的时候会报错识别不到stream功能 安装stream模块 yum insta…

今日分享:Midjourney巧妙地用参考图/垫图来绘画图

大家都知道AI绘画工具每次生成的效果都是随机的&#xff0c;但是现在很多AI绘图工具都提供了利用参考图/垫图的方式出图&#xff0c;这样就可以让让AI画作生成自己想要的布局、场景、色彩等等。 国内的AI绘图工具一般都好操作&#xff0c;国外主流的Midjourney也可以添加参考图…

文件后缀

★图像文件的后缀名 进入多媒体世界后&#xff0c;大家会看到各种各样精彩的图片&#xff0c;会发现许多种后缀名。的确&#xff0c;由于各个公司在开发图形有关的软件时都自制标准&#xff0c;导致今日在图形方面有太多的格式&#xff0c;以下就是常见的几种格式&#xff1a;…

KVM虚拟化技术的-虚拟机配置文件

一、虚拟机配置文件&#xff1a;/etc/libvirt/qemu/ 每个KVM虚拟主机都有自己的配置文件&#xff0c;都是以虚拟主机名命名&#xff1b;KVM虚拟机的配置文件在/etc/libvirt/qemu/下&#xff0c;以xml文件形式存在&#xff1b; [rootnode3 qemu]# virsh list --all …

常见文件扩展名

*.exe‖可执行文件&#xff1b;直接打开 *.rar‖一种压缩包&#xff1b;用WinRAR打开 *.zip‖一种压缩包&#xff1b;用WinRAR打开&#xff0c;或者WinXP也可以直接打开 *.iso‖虚拟光驱&#xff1b;用WinRAR打开&#xff0c;也可用其他虚拟光驱软件 *.doc‖word文档&#xff1…

mac碰到哪些情况下需要重装系统?

最近有很多朋友问到&#xff1a;Mac 如何重装/降级系统&#xff1f;为了方便大家理解和吸收&#xff0c;mac小编把这个系列文章分成了几篇&#xff0c;主要包括&#xff1a;哪些情况下需要重装系统&#xff1f;重装系统方法有哪些&#xff1f;具体该如何操作&#xff1f;以及我…