Android的自动更新和版本控制

最近做一个快递柜终端的项目,在每台快递柜上都需要安装一个平板来控制快递箱的打开和关闭,但是因为快递柜数量巨大,而且分布于各个小区,所以当需要更新设备的时候,不可能人工对其进行操作,需要在程序中对其增加自动更新功能。

自动更新之前,首先通过长连接或者定时检查更新(我这里是使用长连接)来向服务器发送请求,获取服务器最新的版本号,然后我们要获取到当前APP的版本号,代码如下:

    /**
     * 获取APP的版本号
     * @return
     */
public String getVersionName() {

    PackageManager packageManager = getPackageManager();

    PackageInfo packageInfo;

    String versionName = "";

    try {

        packageInfo = packageManager.getPackageInfo(getPackageName(), 0);

        versionName = packageInfo.versionName;

    } catch (PackageManager.NameNotFoundException e) {

        e.printStackTrace();

    }

    return versionName;

}

获取到服务器的版本号,与当前APP的版本好进行比较,然后我增加了获取谁技术

 public void showVersion(AppUpdateModel appUpdateModel) {
        if (!appUpdateModel.getVersion().equals(getVersionName())) {//检查版本号不一致时更新
            updateType = appUpdateModel.getUpdateType();
            //延迟下载
            Random r = new Random();//获取一个
            long startTime = (long) (r.nextFloat() * 1000 * 60 * 1); //获取一个0~10分钟的随机时间,进行延迟操作。
            LogUtils.loge(TAG, "延迟" + startTime + "ms后开始更新");
            downloadHandler = null;
            downloadHandler = new Handler();//开启Handler线程
            downloadHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                   createTask(url).start();//开始下载更新,详细代码在下面
                }
            }, startTime);

        } else {
            Log.i(TAG, "与当前版本一致,无须更新");
        }

        md5 = appUpdateModel.getMd5();//服务器发来的md5加密

    }

下载更新,我这里使用FileDownloader库 【Github地址】(https://github.com/lingochamp/FileDownloader),详细使用请看地址。

 //从新下载次数。
    protected int reDownTimes = 0;
    public static final String SDCARD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
    public static final String BASE_PAT = SDCARD_PATH + File.separator + "DXAccessControl" + File.separator;
    public static final String DOWNLOAD_PATH = BASE_PAT +  "downloadAPK" + File.separator;//下载到sd的地址

    public BaseDownloadTask createTask(final String url) {


        File file = new File(DOWNLOAD_PATH + "temp.apk");
        return FileDownloader.getImpl().create(url)
                //  如果pathAsDirectory是true,path就是存储下载文件的文件目录(而不是路径),此时默认情况下文件名filename将会默认从response#header中的contentDisposition中获得
                .setPath(file.getAbsolutePath(), false)
                .setCallbackProgressTimes(300)//设置整个下载过程中FileDownloadListener#progress最大回调次数
                .setMinIntervalUpdateSpeed(400)//设置下载中刷新下载速度的最小间隔
                .setListener(new FileDownloadSampleListener() {//设置监听,可以以相同监听组成队列

                    //等待,已经进入下载队列
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        super.pending(task, soFarBytes, totalBytes);
                        LogUtils.loge(TAG, "pending");

                    }

                    //下载进度回调
                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        super.progress(task, soFarBytes, totalBytes);
                        String a = String.format("%.0f", (double) soFarBytes / (double) totalBytes * 100);
                        LogUtils.loge(TAG, "apk downloading " + a + "%");
                    }

                    //下载出现错误
                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        super.error(task, e);
                        new File(DOWNLOAD_PATH + "temp.apk").delete();
                        LogUtils.loge(TAG, "error=" + e.toString());

                        if (reDownTimes < 10) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    reDownTimes++;
                                    createTask(url).start();
                                }
                            }, 1000 * 15);
                        } else {
                            reDownTimes = 0;


                        }
                        e.printStackTrace();
                    }

                    //已经连接上
                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                        super.connected(task, etag, isContinue, soFarBytes, totalBytes);
                        LogUtils.loge(TAG, "connected");

                    }

                    //暂停下载
                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        super.paused(task, soFarBytes, totalBytes);
                        LogUtils.loge(TAG, "paused");

                    }

                    //完成整个下载过程
                    @Override
                    protected void completed(BaseDownloadTask task) {
                        super.completed(task);

                       //对文件的md5进行判断是否一致,如果后台没有返回可以忽略这一步
                       if (md5.equals(FileHelper.getMd5ByFile(new File(DOWNLOAD_PATH + "temp.apk")))) {
                            Log.i(TAG, "updateType=" + updateType);
                            if (updateType == 1) {//通过后台发送的值选择是立刻更新还是凌晨更新
                                //   showMsg("即时更新");
                                new File(DOWNLOAD_PATH + "temp.apk").renameTo(new File(AppApplication.DOWNLOAD_PATH + "aa.apk"));
                                //安装app
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.setDataAndType(Uri.fromFile(new File(DOWNLOAD_PATH + "aa.apk")), "application/vnd.android.package-archive");
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                Intent intent1 = new Intent(AppApplication.INSTALL_REBOOT_ACTION);
                                intent1.putExtra("install", true);
                                sendBroadcast(intent1);//向底层发送广播,如果不需要自动安装可以忽略
                            } else {
                                //凌晨安装
                                String local = "GMT+8";
                                Calendar c = new GregorianCalendar(TimeZone.getTimeZone(local));
                                c.setTimeInMillis(Calendar.getInstance().getTimeInMillis());
                                c.set(Calendar.HOUR_OF_DAY, 2);
                                c.set(Calendar.MINUTE, 20);
                                c.set(Calendar.SECOND, 0);
                                long delay = c.getTimeInMillis() - System.currentTimeMillis();
                                if (c.getTimeInMillis() - System.currentTimeMillis() < 0) {
                                    delay += 24 * 60 * 60 * 1000;
                                }
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        new File(AppApplication.DOWNLOAD_PATH + "temp.apk").renameTo(new File(AppApplication.DOWNLOAD_PATH + "aa.apk"));
                                        Log.i(TAG, "开始安装");
                                        //判断disRestart是否存在,如果不存在就创建,否则不创建
                                        //安装app
                                        Intent intent = new Intent(Intent.ACTION_VIEW);
                                        intent.setDataAndType(Uri.fromFile(new File(AppApplication.DOWNLOAD_PATH + "aa.apk")), "application/vnd.android.package-archive");
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(intent);
                                        Intent intent1 = new Intent(AppApplication.INSTALL_REBOOT_ACTION);
                                        intent1.putExtra("install", true);
                                        sendBroadcast(intent1);
                                    }
                                }, delay);
                                Log.i(TAG, "update after " + delay + "ms");
                            }
                        } else {
                            new File(DOWNLOAD_PATH + "temp.apk").delete();//下载完成后删除文件
                        
                        }

                        //  }


                    }

                    //在下载队列中(正在等待/正在下载)已经存在相同下载连接与相同存储路径的任务
                    @Override
                    protected void warn(BaseDownloadTask task) {
                        super.warn(task);
                        LogUtils.loge(TAG, "warn");

                    }
                });
    }

在输入地址之后,开始下载,当下载途中出现网络错误或者下载失败的情况,可以重新下载,reDownTimes 表示当前下载的次数,我这里设为10次,下载失败,15秒后会重新下载。
当下载完成之后,会将该app存储到对应的地址,并且通过底层发送广播,即可自动安装apk,注意,这里要保证build.gradle里的versionCode不一致才能成功安装。
我这里因为是快递柜,防止用户操作的时候,突然更新,所以增加了延迟操作,到凌晨才进行更新。
PS:这里会涉及底层系统的自动安装的源码修改,这里没有写明,主要是写应用层的。

你可能感兴趣的:(Android的自动更新和版本控制)