关于版本更新的方案选择,强制更新以及提示更新

 public static String UPDATE_PROVIDER = "com.xxx.xxx.provider";//包名+provider
    private String mDesc;
    private int isNeedUpdate;
    private String packUrl;
    private MDialog progressBardialog;
    private String appName;
    private String mVersionName;
    private ProgressBar progressBar;
    private TextView mtvNumber;
    MDialog.Builder builder;
    private MDialog mDialog;
 private void checkVersion() {
        HashMap<String, String> map = new HashMap<>();
        map.put(Constant.VERSION, AppUtil.getApplicaionVersionName(mContext));//
        map.put("deviceType", "0");//手机类型(0、android 1、iphone)
        PackOkHttpUtils.postHttp(this, HttpBaseBean.class, ApiConfig.SYS_VERSION_INFO, false,
                map, new PackOkHttpUtils.HttpCallBackListener<HttpBaseBean>() {
                    @Override
                    public void onSuccess(HttpBaseBean baseBean, String response) {
                        if (baseBean.getCode() == Constant.HTTP_SUCCESS) {
                            VersionInfoBean versionInfoBean = JsonUtils.fromJson(response,
                                    VersionInfoBean.class);
                            if (versionInfoBean.getData() != null && !MStringUtils.isNullOrEmpty
                                    (versionInfoBean.getData().getUrl()) && !MStringUtils.isNullOrEmpty(versionInfoBean.getData().getCodeX())) {

                                String newVersion = versionInfoBean.getData().getCodeX();
                                int newVcode = Integer.parseInt(newVersion);
                                int oldVcode = AppUtil.getVersionCode(mContext);
                                if (newVcode > oldVcode) {
                                    appName = versionInfoBean.getData().getName();
                                    packUrl = versionInfoBean.getData().getUrl();
                                    isNeedUpdate = versionInfoBean.getData().getMust();//0提示更新  ; 1强制更新
                                    mDesc = versionInfoBean.getData().getMessage();
                                    mVersionName = versionInfoBean.getData().getCodeX();
                                    if (builder == null) {
                                        dialogForUpdate(mVersionName, mDesc, appName, packUrl);
                                    }
                                    if (!SPUtils.getString("Later").equals("Later")) {
                                        handler.sendEmptyMessageDelayed(99, 1000);
                                    }
                                }
                            } 
                        }
                    }

                    @Override
                    public void onError(String response) {

                    }
                });

    }

    @Override
    protected void onStart() {
        super.onStart();
        checkVersion();//检查更新我放在onstart方法里面是方便用户在每次回到这个界面的时候都能检测到更新
    }

private void dialogForUpdate(String versionName, String desc, final String appName,
                                 final String packUrl) {

        builder = new MDialog.Builder(this, "检测到最新版本:" + versionName, desc);
        builder.isConLeft(true);
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (isNeedUpdate == 1) {
                    PermissionGen.with(MainActivity.this)
                            .addRequestCode(50)
                            .permissions(
                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                            ).request();
                    getLatestVersion();
                } else if (isNeedUpdate == 0) {
                    //启动服务
                    Intent intent = new Intent(MainActivity.this, DownloadService.class);
                    intent.putExtra("appName", appName);
                    intent.putExtra("url", packUrl);
                    startService(intent);
                }
            }
        });
        builder.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SPUtils.putString("Later", "Later");
                dialog.dismiss();

            }
        });
        if (isNeedUpdate == 1) {
            builder.isNega(false);
            builder.setCancelable(false);
        } else {
            builder.isNega(true);
            builder.setCancelable(true);
        }
        mDialog = builder.create();
    }

private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 99:
                    if (AppUtil.isForeground(mContext, getComponentName()
                            .getClassName())) {
                        if (!mDialog.isShowing()) {
                            mDialog.show();
                        }
                    }
                    break;
            }
            return false;
        }
    });

 private void getLatestVersion() {
        if (packUrl != null) {
            progressBardialog.setCancelable(true);
            progressBardialog.setCanceledOnTouchOutside(false);
            progressBar.setMax(100);
            progressBardialog.show();
            progressBardialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent
                            .ACTION_DOWN) {
                        setAdvToast();
                        dismiss();
                    }
                    return false;
                }
            });
            downLoad();
        }
    }

    private void downLoad() {
        if (MStringUtils.isNullOrEmpty(appName)) {
            appName = "yudaosz.apk";
        }
        OkHttpUtils.get()
                .url(packUrl)
                .headers(PackOkHttpUtils.getHeadsMap(this))
                .tag(MainActivity.class)
                .addParams("version", AppUtil.getApplicaionVersionName(getApplicationContext()))
                .build()
                .execute(new FileCallBack(Environment.getExternalStoragePublicDirectory
                        (Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), appName) {
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        int progressInt = (int) (progress * 100);
                        progressBar.setProgress(progressInt);
                        mtvNumber.setText(progressInt + "%");
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyToast.showMessage("下载失败");
                    }

                    @Override
                    public void onResponse(File response, int id) {

                        try {
                            SPUtils.putBoolean("VersionUpdate", false);
                            String authority = UPDATE_PROVIDER;
                            Uri fileUri = FileProvider.getUriForFile(getApplicationContext(),
                                    authority, response);
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            //7.0以上需要添加临时读取权限
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                intent.setDataAndType(fileUri, "application/vnd.android" +
                                        ".package-archive");
                            } else {
                                Uri uri = Uri.fromFile(response);
                                intent.setDataAndType(uri, "application/vnd.android" +
                                        ".package-archive");
                            }

                            startActivity(intent);
                            //弹出安装窗口把原程序关闭。
                            //避免安装完毕点击打开时没反应
                            killProcess(android.os.Process.myPid());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });


    }

    private void dismiss() {
        if (isFinishing()) {
            return;
        }
        if (null != progressBardialog && progressBardialog.isShowing()) {
            progressBardialog.dismiss();
            OkHttpUtils.getInstance().cancelTag(MainActivity.class);
            MyToast.showMessage("取消更新");
        }
    }


    private void progressBarDialog() {
        progressBardialog = new MDialog(mContext, R.style.Dialog);
        View layoutUpdate = LayoutInflater.from(mContext).inflate(R.layout.dialog_update_layout,
                null);
        progressBardialog.addContentView(layoutUpdate, new ViewGroup.LayoutParams(ViewGroup
                .LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        progressBardialog.setCancelable(false);
        progressBar = (ProgressBar) layoutUpdate.findViewById(R.id.mpb_update);
        progressBardialog.setContentView(layoutUpdate);
        mtvNumber = (TextView) layoutUpdate.findViewById(R.id.mtv_number);
    }

public class DownloadService extends Service {//下载服务

    //定义notify的id,避免与其它的notification的处理冲突
    private static final int NOTIFY_ID = 0;

    private NotificationManager mNotificationManager;
    private NotificationCompat.Builder mBuilder;

    //定义个更新速率,避免更新通知栏过于频繁导致卡顿
    private float rate = .0f;
    private String url;
    private String appName;
    private String target;
//    private TextView mtvNumber;
//    private MDialog progressBardialog;
//    private ProgressBar progressBar;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        MLog.e("fuwu", "laile");
        return null;
    }

    @Override
    public void unbindService(ServiceConnection conn) {
        super.unbindService(conn);
        mNotificationManager.cancelAll();
        mNotificationManager = null;
        mBuilder = null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        appName = intent.getStringExtra("appName");

        if (MStringUtils.isNullOrEmpty(appName)) {
            appName = "xysz.apk";
        }

        url = intent.getStringExtra("url");
        //创建下载APK的路径
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            target = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        }


        setNotification();
        // 通过通知管理器发送通知֪
        if (url != null) {
            downApk(url);
        }
        handler.sendEmptyMessage(0);
        return super.onStartCommand(intent, flags, startId);
    }


    /**
     * 创建通知栏
     */
    private void setNotification() {
        if (MStringUtils.isNullOrEmpty(url)) {
            complete("下载路径错误");
            return;
        }
        if (mNotificationManager == null)
            mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this);

        mBuilder.setContentTitle("开始下载")
                .setAutoCancel(true)//打开程序后图标消失
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText("正在下载:")
                .setTicker("CraveHome开始下载")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setOngoing(true)
                .setAutoCancel(true)
                .setWhen(System.currentTimeMillis());
        mNotificationManager.notify(NOTIFY_ID, mBuilder.build());
    }

    /**
     * 下载完成
     */
    private void complete(String msg) {
        if (mBuilder != null) {
            mBuilder.setContentTitle("新版本").setContentText(msg);
            Notification notification = mBuilder.build();
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            mNotificationManager.notify(NOTIFY_ID, notification);
        }
        stopSelf();
    }


    /**
     * 开始下载apk
     */
    public void downApk(String url) {

        OkHttpUtils.get()
                .url(url)
                .headers(PackOkHttpUtils.getHeadsMap(this))
                .tag(this)
                .addParams(Constant.VERSION, AppUtil.getApplicationVersionName()) TODO: 2018/5/25
                .build()
                .execute(new FileCallBack(target, appName) {
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        int progressInt = (int) (progress * 100);
                        Message message = Message.obtain();
                        message.what = 2;
                        message.obj = progressInt;
                        handler.sendMessage(message);
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Message message = Message.obtain();
                        message.what = 1;
                        message.obj = "下载错误";
                        handler.sendMessage(message);
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        try {
                            SPUtils.putBoolean("VersionUpdate", false);
                            String authority = UPDATE_PROVIDER;
                            Uri fileUri = FileProvider.getUriForFile(getApplicationContext(), authority, response);
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                            //7.0以上需要添加临时读取权限
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
                            } else {
                                Uri uri = Uri.fromFile(response);
                                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                            }

                            startActivity(intent);
                            stopSelf();
                            //弹出安装窗口把原程序关闭。
                            //避免安装完毕点击打开时没反应
                            killProcess(android.os.Process.myPid());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }


    /**
     * 路径为根目录
     * 创建文件名称为 updateDemo.apk
     */
    private File createFile() {
        String root = Environment.getExternalStorageDirectory().getPath();
        File file = new File(root, "yudaosz.apk");
        if (file.exists())
            file.delete();
        try {
            file.createNewFile();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 把处理结果放回ui线程
     */
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    MyToast.showMessage("下载开始");
//                    progressBarDialog();
                    break;

                case 1:
                    mNotificationManager.cancel(NOTIFY_ID);
                    MyToast.showMessage((String) msg.obj);
                    stopSelf();
                    break;

                case 2: {
                    int progress = (int) msg.obj;
                    mBuilder.setContentTitle("正在下载:新版本...")
                            .setContentText(String.format(Locale.CHINESE, "%d%%", progress))
                            .setProgress(100, progress, false)
                            .setWhen(System.currentTimeMillis());
//                    progressBar.setProgress(progress);
                    Notification notification = mBuilder.build();
                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    mNotificationManager.notify(NOTIFY_ID, notification);
                }
                break;

            }
            return false;
        }
    });


    /**
     * 是否运行在用户前面
     */
    private boolean onFront() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null || appProcesses.isEmpty())
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(getPackageName()) &&
                    appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    /**
     * 销毁时清空一下对notify对象的持有
     */
    @Override
    public void onDestroy() {
        mNotificationManager = null;
        super.onDestroy();
    }


}
  <!-- manifest注册更新服务 -->
        <service android:name=".service.DownloadService"/>
 <!-- 适配7.0系统数据   android:authorities= "包名.provider" -->
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.xxx.xxx.provider"  
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

下面是provider_paths的内容

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <paths>
        <external-path name="download"  path=""/>
    </paths>
</resources>



//Splash界面 “提示更新”的默认值,默认为空
        SPUtils.putString("Later", "");






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

material_无机化学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值