Android简单的软件app更新升级

软件更新主要分为两步,一是从服务器中下载apk,二是下载完后把下载的apk进行安装,当然还有很多细节,比如下载apk前先校验软件版本号,本项目就不对这些细节做处理了,直接来简单暴力通用的。

首先下载服务器上的apk, serverPath表示服务器地址, savedPath表示保存下载的apk路径,一定一步一步的mkdirs,apk的名字换成你要下载的包名,ProgressDialog可以在前面写好,再传进来。

ProgressDialog proDialog = android.app.ProgressDialog.show(this, "提示", "正在下载,请稍后...");

public static File download(String serverPath, String savedPath, ProgressDialog pd) {

    try {
        URL url = new URL(serverPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(10000);
        conn.setRequestMethod("GET");
        int code = conn.getResponseCode();
        if (code == 200) {
            int fileSize = conn.getContentLength() / 1024;
            pd.setMax(fileSize);
            int total = 0;
            InputStream is = conn.getInputStream();
            File file01 = new File(savedPath);
            if (!file01.exists()) {
                file01.mkdirs();
            }
            File file = new File(file01.getAbsolutePath(), "baiduyinyue_4802.apk");
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += (len / 1024);
                pd.setProgress(total);
            }
            fos.flush();
            fos.close();
            is.close();
            pd.dismiss();
            return file;
        } else {
            pd.dismiss();
            return null;
        }
    } catch (Exception e) {
        pd.dismiss();
        e.printStackTrace();
        Log.e("TAG", "异常: " + e.getMessage());
        return null;
    }
}

第二步就是下载的apk进行安装

    private void installApk(File file) {

    Intent intent = new Intent();
    intent.setAction("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    MainActivity.this.startActivity(intent);
}

这里提供一个apk下载地址供大家测试 http://gdown.baidu.com/data/wisegame/fd84b7f6746f0b18/baiduyinyue_4802.apk 。保存地址不能放在sd卡的根目录,最好在新建的文件夹里。

你可能感兴趣的:(原创)