APP自动检测版本及更新 - Android

我们偶尔会对自己的APP做更新,那么不免就需要把最新版本的app推送给用户,所以今天动手实现一下app自动检测版本及更新。实现思路大致是这样的:
1、首先我们在服务器上建立一个version.txt文件,提供给客户端最新版本的信息,内容如下:

//json数据格式
{"code":"2.0","update":"最新版本apk的地址"}

2、在启动页中获取本机版本,并开启线程获取服务器的version.txt,并解析出最新版本号与本机对比。(通常在与服务器交互前,我会先ping一下服务器,来确保服务器以及网络可用。)
3、如果版本号不同,那么就提示用户版本需要升级。
4、当用户同意升级,那么就下载最新版本APK,并自动安装。

大致思路就是这样,接着上代码。

通过ping服务器,判断服务器是否可用。

/**
     * 通过ping判断是否可用
     * @return
     */
    public static boolean ping() {
        try {
            //服务器ip地址
            String ip = "***";
            Process p = Runtime.getRuntime().exec("ping -c 1 -w 100 " + ip);
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content;
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            int status = p.waitFor();
            if (status == 0) {
                return true;
            }
        }
        catch (IOException e) {}
        catch (InterruptedException e) {}
        return false;
    }

从服务器获取APP最新版本信息。


/**
     * 获取最新版本信息
     * @return
     * @throws IOException
     * @throws JSONException
     */
    private String getVersion() throws IOException, JSONException {
        URL url = new URL("http://***/version.txt");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setReadTimeout(8 * 1000);
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String string;
        string = bufferedReader.readLine();
        //对json数据进行解析
        JSONObject jsonObject = new JSONObject(string);
        String strings = jsonObject.getString("code");
        return strings;
    }

弹出对话框,用户点击确定开始下载最新版本APK,点击取消不做任何动作。

/**
     * 弹出对话框
     */
    protected void showUpdataDialog() {
        AlertDialog.Builder builer = new AlertDialog.Builder(this) ;
        builer.setTitle("版本升级");
        builer.setMessage("软件更新");
        //当点确定按钮时从服务器上下载 新的apk 然后安装
        builer.setPositiveButton("确定", (dialog, which) -> downLoadApk());
        //当点取消按钮时不做任何举动
        builer.setNegativeButton("取消", (dialogInterface, i) -> {});
        AlertDialog dialog = builer.create();
        dialog.show();
    }

开始从服务器下载APK

    protected void downLoadApk() {
        //进度条
        final ProgressDialog pd;
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.show();
        new Thread(){
            @Override
            public void run() {
                try {
                    File file = getFileFromServer("http://***/v.apk", pd);
                    //安装APK
                    installApk(file);
                    pd.dismiss(); //结束掉进度条对话框
                } catch (Exception e) {
                }
            }}.start();
    }
public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //获取到文件的大小
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len ;
            int total=0;
            while((len =bis.read(buffer))!=-1){
                fos.write(buffer, 0, len);
                total+= len;
                //获取当前下载量
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        }
        else{
            return null;
        }
    }

最后通过Intent动作启动安装APK

protected void installApk(File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }

《APP自动检测版本及更新 - Android》 Screenshot_1489932904.png
《APP自动检测版本及更新 - Android》 Screenshot_1489932913.png

笔者能力有限,不足之处欢迎指出!

    原文作者:麦兜叮叮当
    原文地址: https://www.jianshu.com/p/2818d062a8f0
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞