OK更新下载新版本模版

获取当前版本号:判断是否更新,是否强制更新:再进行下载新版本apk
public class VersionUtils {
    public static String getVersionName(Context context) {
        String versionName = "";
        PackageManager packageManager = context.getPackageManager();
        String packageName = context.getPackageName();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

}

这里有个APK路径:

String path = "/download/";
String url = "http://www.wuxirui.com/download/jinritoutiao.apk";

上代码:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
    File directory = Environment.getExternalStorageDirectory();
    // /sdcard/download/  获取的是下载的文件放在哪的地址
    String absolutePath = directory.getAbsolutePath();
    path = absolutePath + path;
}

if (url.contains(".")) {   //获取apk的名字和后面的样式jinritoutiao.apk
    String typeName = url.substring(url.lastIndexOf(".") + 1);
    if (url.contains("/")) {
        String filename = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
        path = path + filename + "." + typeName;   //拼接最终的下载到本地的路径
    }
}
OKHttpUtil.getInstence().download(url, new File(path), new DownloadCallback() {//自己写的接口回调,三个
    @Override
    public void onSucc(String string) {
        Log.e("Download","完成");
        installApk(new File(path));   //自动安装Apk
    }
    @Override
    public void onFals(Exception ex) {
        Log.e("Download",ex.getMessage());
    }
    @Override
    public void onPress(long press) {
        Log.e("Download",press+"");
        int pro = (int) press;
        progressBar.setProgress(pro);   //更新进度条
    }
});
/**
 * 自动安装apk
 * @param file
 */
private void installApk(File file) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.addCategory("android.intent.category.DEFAULT");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    startActivity(intent);
    android.os.Process.killProcess(android.os.Process.myPid());
}
//下载Apk网络请求
public void download(String url, final File file, final DownloadCallback downloadCallback){
    // 父目录是否存在
    File parent = file.getParentFile();
    if (!parent.exists()) {
        parent.mkdir();
    }
    // 文件是否存在
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Request request = new Request.Builder()
            .url(url)
            .build();
    OkHttpClient okClient = new OkHttpClient();
    okClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, final IOException e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    downloadCallback.onFals(e);   //这些接口回调的方法自己写写
                }
            });
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                long totaLenght = response.body().contentLength();   //获取responce的长度
                InputStream inputStream = response.body().byteStream();
                FileOutputStream outputStream = new FileOutputStream(file);
                byte[] buffer = new byte[2048];
                int len = 0;
                int sum = 0;
                while ((len = inputStream.read(buffer)) != -1){
                    sum+=len;  //每次循环获取下载的长度
                    final long pregress = sum * 100 / totaLenght;   //每次循环获取下载和总下载所占的百分比
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            downloadCallback.onPress(pregress);   //进度条的进度
                        }
                    });
                    outputStream.write(buffer,0,len);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
                //这个不用Handler转换主线程,下载东西不用
                downloadCallback.onSucc(file.getAbsolutePath());
            }

        }
    });
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值