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

时间:2025-01-20 07:02:31
 public static String UPDATE_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;
     builder;
    private MDialog mDialog;
 private void checkVersion() {
        HashMap<String, String> map = new HashMap<>();
        (, (mContext));//
        ("deviceType", "0");//手机类型(0、android 1、iphone)
        (this, , ApiConfig.SYS_VERSION_INFO, false,
                map, new <HttpBaseBean>() {
                    @Override
                    public void onSuccess(HttpBaseBean baseBean, String response) {
                        if (() == Constant.HTTP_SUCCESS) {
                            VersionInfoBean versionInfoBean = (response,
                                    );
                            if (() != null && !
                                    (().getUrl()) && !(().getCodeX())) {

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

                    @Override
                    public void onError(String response) {

                    }
                });

    }

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

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

        builder = new (this, "检测到最新版本:" + versionName, desc);
        (true);
        ("立即更新", new () {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (isNeedUpdate == 1) {
                    ()
                            .addRequestCode(50)
                            .permissions(
                                    .READ_EXTERNAL_STORAGE,
                                    .WRITE_EXTERNAL_STORAGE
                            ).request();
                    getLatestVersion();
                } else if (isNeedUpdate == 0) {
                    //启动服务
                    Intent intent = new Intent(, );
                    ("appName", appName);
                    ("url", packUrl);
                    startService(intent);
                }
            }
        });
        ("稍后再说", new () {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ("Later", "Later");
                ();

            }
        });
        if (isNeedUpdate == 1) {
            (false);
            (false);
        } else {
            (true);
            (true);
        }
        mDialog = ();
    }

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

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

    private void downLoad() {
        if ((appName)) {
            appName = "";
        }
        ()
                .url(packUrl)
                .headers((this))
                .tag()
                .addParams("version", (getApplicationContext()))
                .build()
                .execute(new FileCallBack(
                        (Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), appName) {
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        (progress, total, id);
                        int progressInt = (int) (progress * 100);
                        (progressInt);
                        (progressInt + "%");
                    }

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

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

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

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


    }

    private void dismiss() {
        if (isFinishing()) {
            return;
        }
        if (null != progressBardialog && ()) {
            ();
            ().cancelTag();
            ("取消更新");
        }
    }


    private void progressBarDialog() {
        progressBardialog = new MDialog(mContext, );
        View layoutUpdate = (mContext).inflate(.dialog_update_layout,
                null);
        (layoutUpdate, new (ViewGroup
                .LayoutParams.MATCH_PARENT, .WRAP_CONTENT));
        (false);
        progressBar = (ProgressBar) (.mpb_update);
        (layoutUpdate);
        mtvNumber = (TextView) (.mtv_number);
    }

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

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

    private NotificationManager mNotificationManager;
    private  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) {
        ("fuwu", "laile");
        return null;
    }

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

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

        if ((appName)) {
            appName = "";
        }

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


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


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

        ("开始下载")
                .setAutoCancel(true)//打开程序后图标消失
                .setSmallIcon(.ic_launcher)
                .setContentText("正在下载:")
                .setTicker("CraveHome开始下载")
                .setSmallIcon(.ic_launcher)
                .setLargeIcon((getResources(), .ic_launcher))
                .setOngoing(true)
                .setAutoCancel(true)
                .setWhen(());
        (NOTIFY_ID, ());
    }

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


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

        ()
                .url(url)
                .headers((this))
                .tag(this)
                .addParams(, ()) TODO: 2018/5/25
                .build()
                .execute(new FileCallBack(target, appName) {
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        (progress, total, id);
                        int progressInt = (int) (progress * 100);
                        Message message = ();
                         = 2;
                         = progressInt;
                        (message);
                    }

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

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

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

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

                    }
                });
    }


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

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

                case 1:
                    (NOTIFY_ID);
                    ((String) );
                    stopSelf();
                    break;

                case 2: {
                    int progress = (int) ;
                    ("正在下载:新版本...")
                            .setContentText((, "%d%%", progress))
                            .setProgress(100, progress, false)
                            .setWhen(());
//                    (progress);
                    Notification notification = ();
                     = Notification.FLAG_AUTO_CANCEL;
                    (NOTIFY_ID, notification);
                }
                break;

            }
            return false;
        }
    });


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

        for ( appProcess : appProcesses) {
            if ((getPackageName()) &&
                     == .IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

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


}
  <!-- manifest注册更新服务 -->
        <service android:name="."/>
 <!-- 适配7.0系统数据   android:authorities= "包名.provider" -->
        <provider
            android:name="."
            android:authorities=""  
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name=".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界面 “提示更新”的默认值,默认为空
        ("Later", "");