apk检查更新下载安装

package com.example.boot.utils;


import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;


import com.example.boot.contant.Contant;
import com.example.boot.domain.VersionInfo;
import com.example.boot.mychangeonpage.R;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * Created by p on 2017/07/12.
 */


public class UpdateManager {
    private Activity context;
    private ProgressDialog pBar;
    private File file;
    final String url = Contant.HTTP_DOWN;
    //判断是否强制更新  1:强制更新  0:非强制更新
    private String isUp = "";
    //下载进度
    private int total = 0;
    private int progress = 0;
    //正在下载
    public static final int DOWNLOAD_ING = 1;
    //下载完成
    public static final int DOWNLOAD = 2;
    //下载失败
    public static final int DOWNLOAD_FAILED = 3;
    public static final int DOWNLOAD_FAILED_IO = 4;
    private AlertDialog alertDialog;
    private VersionInfo versionInfo;


    public UpdateManager(Activity context, VersionInfo versionInfo) {
        this.context = context;
        this.versionInfo = versionInfo;
    }


    public UpdateManager(Activity context) {
        this.context = context;
    }


    //升级显示弹出框
    public void showDialogUpdate() {
        final String ver = versionInfo.getVersionNo();
        //判断是否强制更新
        isUp=versionInfo.getIsForeceUpdate();
        // 这里的属性可以一直设置,因为每次设置后返回的是一个builder对象
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        // 设置提示框的标题
        builder.setTitle("版本升级").
                setIcon(R.mipmap.ic_launcher).
                setMessage("当前版本:" + getVersionNo() + "\n" + "更新版本:" + ver + "\n" + "更新内容:" +
                        versionInfo.getUpdateContent()).
                setCancelable(false).
                setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {                       
                            downFile(url);                           
                        } else {
                            Toast.makeText(context, "SD卡不可用,请插入SD卡",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
        if ("1".equals(isUp)) {
              builder.setNegativeButton("以后更新", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialogInterface, int i) {
                      context.finish();
                  }
              });
        } else if ("0".equals(isUp)) {
            builder.setNegativeButton("稍后更新", null);
        }
        // 生产对话框
        alertDialog = builder.create();
        // 显示对话框
        alertDialog.show();
    }


    //下载apk
    public void downFile(final String url) {
        pBar = new ProgressDialog(context);    //进度条,在下载的时候实时更新进度,提高用户友好度
        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pBar.setTitle("正在下载");
        pBar.setMessage("请稍候...");
        pBar.setCanceledOnTouchOutside(false);
        pBar.setCancelable(false);
        pBar.setProgress(0);
        pBar.show();
        new Thread() {
            public void run() {
                try {
                    URL ur = new URL(url);
                    Log.e("down=", url);
                    HttpURLConnection conn = (HttpURLConnection) ur.openConnection();
                    conn.setConnectTimeout(400000);
                    conn.setRequestProperty("Accept-Encoding", "identity");
                    conn.connect();
                    Log.e("code=", conn.getResponseCode() + "");
                    FileOutputStream fos = null;
                    BufferedInputStream bis = null;
                    InputStream is = null;
                    if (conn.getResponseCode() == 200) {
                        //获取到文件的大小
                        int lengthMax = conn.getContentLength();
                        Log.e("ContentLength=", lengthMax + "");
                        pBar.setMax(100);
                        is = conn.getInputStream();
                        long time = System.currentTimeMillis();//当前时间的毫秒数
                        file = new File(Environment.getExternalStorageDirectory(), time + "sinolube.apk");
                        fos = new FileOutputStream(file);
                        bis = new BufferedInputStream(is);
                        byte[] buffer = new byte[64];
                        int len;
                        while ((len = bis.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                            total += len;
                            //获取当前下载量
                            progress = (int) (((float) total / lengthMax) * 100);
                            handler.sendEmptyMessage(DOWNLOAD_ING);
                            //下载完成
                            if (total == lengthMax) {
                                handler.sendEmptyMessage(DOWNLOAD);
                            }
                        }
                    } else {
                        handler.sendEmptyMessage(DOWNLOAD_FAILED);
                    }
                    fos.close();
                    bis.close();
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    pBar.dismiss();
                    if (e instanceof FileNotFoundException) {
                        PackageManager packageManager = context.getPackageManager();
                        if (!(packageManager.checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                context.getPackageName()) == PackageManager.PERMISSION_GRANTED)) {
                            handler.sendEmptyMessage(DOWNLOAD_FAILED_IO);
                        }
                    } else {
                        handler.sendEmptyMessage(DOWNLOAD_FAILED);
                    }
                }
            }
        }.start();
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD_ING:
                    pBar.setProgress(progress);
                    break;
                case DOWNLOAD:
                    if (pBar != null) {
                        pBar.dismiss();
                        pBar = null;
                    }
                    installApk(file);
                    break;
                case DOWNLOAD_FAILED:
                    Toast.makeText(context, "下载失败,请稍候再试", Toast.LENGTH_SHORT).show();
                    if (pBar != null) {
                        pBar.dismiss();
                        pBar = null;
                    }
                    showDialogUpdate();
//                    context.finish();
                    break;
                case DOWNLOAD_FAILED_IO:
                    Toast.makeText(context, "下载出错,请前往权限设置开启读写手机存储权限。", Toast.LENGTH_SHORT).show();
                    context.finish();
                    break;
            }
        }
    };


    //获得当前版本的VersionNo
    public String getVersionNo() {
        //getPackageName()是你当前类的包名,0代表是获取版本信息
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "获取版本号出错";
        }
    }


    /**
     * 安装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");
//        intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值