Android版本迭代

1.先来说一下实现思路:每次启动应用我们就获取放在服务器上的更新日志(最好保存了最新的版本号,更新内容说明,apk下载地址),我们获取到版本号与当前应用的版本好进行对比,这样我们就可以知道应用是否更新了,废话不多说直接上代码。。




先来说说versionCode和versionName


 versionCode 1//对消费者不可见,仅用于应用市场、程序内部识别版本,判断新旧等用途。 versionName "1.0"//展示给消费者,消费者会通过它认知自己安装的版本. 
 //更新版本修改versionCode的值,必须是int哦 




2.获取服务器上的更新日志信息,需要放在线程中执行哦!






//版本升级apk的地址


    private final String path = "http://www.zgylzb.com/.../update.asp";






    /**


     * 获取升级信息


     * @return


     * @throws Exception


     */


    public UpdateInfo getUpDateInfo() throws Exception {


        StringBuilder sb = new StringBuilder();


        String line;


        BufferedReader reader = null;


        UpdateInfo updateInfo;


        try {


            // 创建一个url对象


            URL url = new URL(path);


            // 通過url对象,创建一个HttpURLConnection对象(连接)


            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();


            urlConnection.setRequestMethod("GET");


            urlConnection.setConnectTimeout(3000);


            urlConnection.setReadTimeout(3000);


            if (urlConnection.getResponseCode() == 200) {


                // 通过HttpURLConnection对象,得到InputStream


                reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));


                while ((line = reader.readLine()) != null) {


                    sb.append(line);


                }


                String info = sb.toString();


                //对升级的信息进行封装


                updateInfo = new UpdateInfo();


                //版本


                updateInfo.setVersion(info.split("&")[1]);


                //升级说明


                updateInfo.setDescription(info.split("&")[2]);


                //apk下载地址


                updateInfo.setUrl(info.split("&")[3]);


                return updateInfo;


            }


        } catch (UnknownHostException e) {


            return null;//连接超时


        } catch (Exception e) {


            e.printStackTrace();//网络请求出错


        } finally {


            try {


                if (reader != null) {


                    reader.close();


                }


            } catch (Exception e) {


                e.printStackTrace();


            }


        }


        return null;


    }
服务器返回的更新数据,最好就使用JSON返回。 


3.这里进行网络访问所以自行添加Internet权限,同时还需要对手机网络进行判断等一系列处理这里就不贴出来了。获取到了版本信息就需要与当前版本进行对比了


if (isNeedUpdate()) {


    showUpdateDialog(); //需要更新版本


}


/**


     * 判断apk是否需要升级


     *


     * @return true需要| false不需要


     */


    private boolean isNeedUpdate() {


        // 最新版本的版本号,info就是上面封装了更新日志信息的对象


        int v = Integer.parseInt(info.getVersion());


        if (server > getVersion())) {


            //需要升级   


            return true;


        } else {


            //不需要升级,直接启动启动Activity


            return false;


        }


    }


//获取当前版本号


private int getVersion() {


        try {


            PackageManager packageManager = getPackageManager();


            PackageInfo packageInfo = packageManager.getPackageInfo(


                    getPackageName(), 0);


            return packageInfo.versionCode;


        } catch (Exception e) {


            e.printStackTrace();


            return -1;


        }


    }


4.需要进行升级,那就把升级信息用对话框展示给用户


/**


     * 显示升级信息的对话框


     */


    private void showUpdateDialog() {


        AlertDialog.Builder builder = new AlertDialog.Builder(WelcomeActivity.this);


        builder.setIcon(android.R.drawable.ic_dialog_info);


        builder.setTitle("请升级APP版本至" + info.getVersion());


        builder.setMessage(info.getDescription());


        builder.setCancelable(false);


        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {


            @Override


            public void onClick(DialogInterface dialog, int which) {


                if (Environment.getExternalStorageState().equals(


                        Environment.MEDIA_MOUNTED)) {


                    downFile(info.getUrl());//点击确定将apk下载


                } else {


                    Toast.makeText(WelcomeActivity.this, "SD卡不可用,请插入SD卡", Toast.LENGTH_SHORT).show();


                }


            }


        });






        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {


            @Override


            public void onClick(DialogInterface dialog, int which) {


                //用户点击了取消


            }


        });


        builder.create().show();


    }


5.下载最新版本的apk


 /**


     * 下载最新版本的apk


     *


     * @param path apk下载地址


     */


    private void downFile(final String path) {


        pBar = new ProgressDialog(WelcomeActivity.this); 


        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);


        pBar.setCancelable(false);


        pBar.setTitle("正在下载...");


        pBar.setMessage("请稍候...");


        pBar.setProgress(0);


        pBar.show();


        new Thread() {


            public void run() {


                try {


                    URL url = new URL(path);


                    HttpURLConnection con = (HttpURLConnection) url.openConnection();


                    con.setReadTimeout(5000);


                    con.setConnectTimeout(5000);


                    con.setRequestProperty("Charset", "UTF-8");


                    con.setRequestMethod("GET");


                    if (con.getResponseCode() == 200) {


                        int length = con.getContentLength();// 获取文件大小


                        InputStream is = con.getInputStream();


                        pBar.setMax(length); // 设置进度条的总长度


                        FileOutputStream fileOutputStream = null;


                        if (is != null) {


                        //对apk进行保存


                            File file = new File(Environment.getExternalStorageDirectory()


                                    .getAbsolutePath(), "home.apk");


                            fileOutputStream = new FileOutputStream(file);


                            byte[] buf = new byte[1024];


                            int ch;


                            int process = 0;


                            while ((ch = is.read(buf)) != -1) {


                                fileOutputStream.write(buf, 0, ch);


                                process += ch;


                                pBar.setProgress(process); // 实时更新进度了


                            }


                        }


                        if (fileOutputStream != null) {


                            fileOutputStream.flush();


                            fileOutputStream.close();


                        }


                        //apk下载完成,使用Handler()通知安装apk


                        handler.sendEmptyMessage(0);


                    }


                } catch (Exception e) {


                    e.printStackTrace();


                }


            }






        }.start();


    }


6.对apk进行安装


//将下载进度对话框取消


pBar.cancel();


//安装apk,也可以进行静默安装


Intent intent = new Intent(Intent.ACTION_VIEW);


intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "home.apk")),


        "application/vnd.android.package-archive");


startActivityForResult(intent, 10);


版本更新基本是就这几个步骤,具体实现还是需要根据公司需求。         
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值