Android App更新版本以及提示用户下载最新apk(有图,有代码,有最终效果图)详细解释及思路

来源:互联网 发布:游戏制作编程 编辑:程序博客网 时间:2024/06/05 21:13

android应用的版本更新,以及推送提示用户最新版本下载代码与逻辑

作为一名Android软件开发的程序员,这个功能是必须要掌握的,因为这个功能不管你是什么app都会用到,除非你这个项目废弃了,因为在我的微信Android技术交流群有许多初学者和刚踏入这个行业不久的程序员经常问道这个问题,我一一回答感觉有的麻烦和不怎么好回答,我干脆跟他们讲我写一篇博客吧,尽量把里面的逻辑和代码写的完善一点吧,这篇文章呢给予一些刚入门或者中级程序员者观看,其中具有我之前开发的思路,以及我写的完善代码和最终效果图,目的:”我们开发人员时不时会对自己的app更新升级,那么就不免需要把最新版本的app推送给用户。

思路概述:大致思路:可提供参考–基本代码逻辑实现出来
1.(后台操作)首先我们在服务器上建立一个版本version.text文件,提供给客户端最新版本的信息,内容如下:这个呢

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

2.在启动页中获取本机的版本信息,并开启线程获取服务器的version.txt,并解析出最新版本号与本机对比。(保证服务器与网络可用:通过ping判断服务器是否可用)
3.如果版本号不同我们就提示用户版本升级。
4 .当用户同意升级,那么就下载最新的版本apk,并自动安装。

以下是以上逻辑的代码:
1.(通过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;    }

2.从服务器获取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;    }

3.弹出对话框,用户点击确定开始下载最新版本的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();    }

4.开始从服务器开始下载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;        }    }

5.最后通过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);    }

以下是效果图这个呢,是我从我的本地为知笔记的截图,因为那个效果图是从我向模拟器截图的,而在为知笔记上截的图保存,只能保存全文,所以下面也是全部文章的一个概括:
这里写图片描述
这个代码都很简单,相信大家都会,主要是这个逻辑,其实这个逻辑也并不复杂,可能使初学者跟小白未接触过的话,可能就有点麻烦,没事!这篇文章我相信大家东能够懂,最后呢要是有大牛觉得我代码中有什么缺陷,或者不够完善的都可以提出来,我会很虚心的向您学习,当然了,有不懂得初学者呢,不懂得地方也可以跟我发邮件,或者直接在下面评论,都可以。我会及时的回复您的。
要是觉得这篇文章可以,那就点个赞吧!

阅读全文
0 0