Files
assistant-android/app/src/main/java/com/gh/gamecenter/manager/UpdateManager.java
2020-06-24 11:54:53 +08:00

366 lines
16 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.gh.gamecenter.manager;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.gh.common.constant.Config;
import com.gh.common.util.DataLogUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.MD5Utils;
import com.gh.common.util.MtaHelper;
import com.gh.common.util.NetworkUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.SpeedUtils;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.R;
import com.gh.gamecenter.entity.AppEntity;
import com.gh.gamecenter.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.halo.assistant.HaloApp;
import com.lightgame.download.DataWatcher;
import com.lightgame.download.DownloadEntity;
import com.lightgame.download.DownloadStatus;
import com.lightgame.download.FileUtils;
import com.lightgame.utils.AppManager;
import com.lightgame.utils.Utils;
import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;
/**
* Created by LGT on 2016/12/8.
* 助手更新 工具类
*/
public class UpdateManager {
// 用于控制第二次打开更新弹窗
private final static String ONCE_ONLY_SECOND_DEFAULT = "ONCE_ONLY_SECOND_DEFAULT";
private final static String ONCE_ONLY_SECOND_CLOSE = "ONCE_ONLY_SECOND_CLOSE";
private final static String ONCE_ONLY_SECOND_OPEN = "ONCE_ONLY_SECOND_OPEN";
private Context mContext;
private SharedPreferences mSp;
private AppEntity appEntity;
private Dialog downloadDialog;
private Dialog loadingDialog;
private ProgressBar app_pb_progress;
private TextView appProgressSize;
private TextView appProgressRemain;
private TextView appProgressPercent;
private View appProgressFilling;
private View appProgressAnchor;
private boolean isShowDownload;
private boolean isChecking;
private DataWatcher dataWatcher = new DataWatcher() {
@Override
public void onDataChanged(DownloadEntity downloadEntity) {
if (downloadEntity.getName().contains("光环助手") && isShowDownload) {
float size = (((float) downloadEntity.getProgress() / 1024) / 1024);
DecimalFormat df = new DecimalFormat("0.00");
appProgressSize.setText((df.format(size) + "MB"));
appProgressRemain.setText(String.format("剩余%s", SpeedUtils.getRemainSecondTime(downloadEntity.getSize(),
downloadEntity.getProgress(), downloadEntity.getSpeed() * 1024)));
app_pb_progress.setProgress((int) (downloadEntity.getPercent() * 10));
int width = app_pb_progress.getWidth();
int marLeft = (int) (downloadEntity.getPercent() / 100 * width);
ViewGroup.LayoutParams anchorLp = appProgressAnchor.getLayoutParams();
if (anchorLp instanceof ConstraintLayout.LayoutParams) {
((ConstraintLayout.LayoutParams) anchorLp).leftMargin = marLeft;
appProgressAnchor.setLayoutParams(anchorLp);
}
ViewGroup.LayoutParams fillingLp = appProgressFilling.getLayoutParams();
fillingLp.width = marLeft + DisplayUtils.dip2px(5);
appProgressFilling.setLayoutParams(fillingLp);
appProgressPercent.setText(((int) downloadEntity.getPercent() + "%"));
if (DownloadStatus.done.equals(downloadEntity.getStatus())) {
DownloadManager.getInstance(mContext).cancel(downloadEntity.getUrl(), false, true);
if (downloadDialog != null) {
downloadDialog.dismiss();
}
if (appEntity != null && appEntity.isForce()) {
AppManager.getInstance().finishAllActivity();
}
} else if (DownloadStatus.neterror.equals(downloadEntity.getStatus())) {
Utils.toast(mContext, "网络错误,请稍后重试");
} else if (DownloadStatus.timeout.equals(downloadEntity.getStatus())) {
Utils.toast(mContext, "请求超时,请稍后重试");
} else if (DownloadStatus.notfound.equals(downloadEntity.getStatus())) {
Utils.toast(mContext, "下载链接异常,请稍后重试");
} else if (DownloadStatus.hijack.equals(downloadEntity.getStatus())) {
Utils.toast(mContext, "网络劫持,请稍后重试");
}
}
}
};
private UpdateManager(Context context) {
mContext = context;
mSp = PreferenceManager.getDefaultSharedPreferences(mContext);
this.isShowDownload = false;
this.isChecking = false;
this.loadingDialog = null;
}
public static UpdateManager getInstance(Context context) {
return new UpdateManager(context);
}
// 检查更新
public void checkUpdate(final boolean isAutoCheck, final Handler handler) {
if (isChecking) {
return;
}
isChecking = true;
if (!isAutoCheck) {
loadingDialog = DialogUtils.showWaitDialog(mContext, "检查更新中...");
}
String channel = HaloApp.getInstance().getChannel();
RetrofitManager.getInstance(mContext).getApi().getUpdate(PackageUtils.getVersionName(), PackageUtils.getVersionCode(), channel)
.map(appEntity -> {
boolean isShowUpdateDialog = false;
// todo 测试环境为了方便测试写死下载链接(测试环境的包链接是不可用的)
if (PackageUtils.getVersionName().contains("-debug") && Config.DEFAULT_CHANNEL.equals(channel)) {
appEntity.setUrl("https://apk2.ghzs.com/upgrade/ghzs4d0_3chTESTid5eec8539957352002f4fcfe8.apk");
}
if (appEntity.getVersionCode() > PackageUtils.getVersionCode()) {
// 助手有更新
UpdateManager.this.appEntity = appEntity;
// 手动更新 强制更新 每次都提示
if (!isAutoCheck || "EVERY_TIME_OPEN".equals(appEntity.getAlert())) {
isShowUpdateDialog = true;
} else if ("ONCE_ONLY".equals(appEntity.getAlert())) {
if (mSp.getBoolean(getUpdateOnceOnlySpKey(), true)) {
isShowUpdateDialog = true;
mSp.edit().putBoolean(getUpdateOnceOnlySpKey(), false).apply();
}
} else if ("ONCE_ONLY_SECOND".equals(appEntity.getAlert())) {
String onceOnlySecond = mSp.getString(getUpdateOnceOnlySecondSpKey(), ONCE_ONLY_SECOND_DEFAULT);
if (ONCE_ONLY_SECOND_OPEN.equals(onceOnlySecond)) {
isShowUpdateDialog = true;
mSp.edit().putString(getUpdateOnceOnlySecondSpKey(), ONCE_ONLY_SECOND_CLOSE).apply();
}
if (ONCE_ONLY_SECOND_DEFAULT.equals(onceOnlySecond)) {
mSp.edit().putString(getUpdateOnceOnlySecondSpKey(), ONCE_ONLY_SECOND_OPEN).apply();
}
} else if (!"NEVER".equals(appEntity.getAlert())) { // 一天提示一次
String showUpdateTime = mSp.getString("show_update_time", null);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String today = format.format(new Date());
if (!today.equals(showUpdateTime)) {
isShowUpdateDialog = true;
mSp.edit().putString("show_update_time", today).apply();
}
}
}
return isShowUpdateDialog ? MD5Utils.getUpdateMD5(appEntity.getUrl(), appEntity.getContent()) : null;
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Response<String>() {
@Override
public void onResponse(String response) {
isChecking = false;
if (loadingDialog != null) {
loadingDialog.dismiss();
}
if (response != null) {
showUpdateDialog(response);
if (handler != null) {
Message message = new Message();
message.what = 0;
message.obj = appEntity.getVersion();
handler.sendMessage(message);
}
} else if (!isAutoCheck) {
Utils.toast(mContext, "已是最新版本");
if (handler != null) {
handler.sendEmptyMessage(1);
}
}
}
@Override
public void onFailure(HttpException e) {
isChecking = false;
if (loadingDialog != null) {
loadingDialog.dismiss();
}
if (!isAutoCheck) {
if (handler != null) {
handler.sendEmptyMessage(1);
}
if (e != null && (e.code() == 304 || e.code() == 404)) {
Utils.toast(mContext, "您的光环助手已是最新版本");
return;
}
Utils.toast(mContext, "检查更新失败");
}
}
});
}
// 显示助手有更新提示框
private void showUpdateDialog(final String md5) {
final Dialog updateDialog = new Dialog(mContext);
Window window = updateDialog.getWindow();
if (window != null) {
window.setBackgroundDrawableResource(android.R.color.transparent);
}
View view = View.inflate(mContext, R.layout.app_update_hint_dialog, null);
View cancelBtn = view.findViewById(R.id.cancel);
TextView content = view.findViewById(R.id.desc);
content.setText(Html.fromHtml(appEntity.getContent()));
TextView version = view.findViewById(R.id.version);
version.setText(String.format("版本%s更新日志", appEntity.getVersion()));
TextView size = view.findViewById(R.id.size);
size.setText(String.format("大小 %s", appEntity.getSize()));
view.setOnClickListener(v -> cancelBtn.performClick());
cancelBtn.setOnClickListener(
v -> {
if (appEntity.isForce()) {
AppManager.getInstance().finishAllActivity();
} else {
updateDialog.dismiss();
}
});
view.findViewById(R.id.confirm).setOnClickListener(
v -> {
updateDialog.dismiss();
String path = FileUtils.getDownloadPath(mContext,
"光环助手V" + appEntity.getVersion() + "_" + md5 + ".apk");
File file = new File(path);
if (file.exists() && file.length() > 0) {
DataLogUtils.uploadUpgradeLog(mContext, "install"); //上传更新安装数据
mContext.startActivity(PackageUtils.getInstallIntent(mContext, path, true));
} else {
MtaHelper.onEvent("软件更新", "下载开始");
showDownloadDialog(md5);
}
});
if (appEntity.isForce()) {
updateDialog.setCanceledOnTouchOutside(false);
updateDialog.setCancelable(false);
}
updateDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
updateDialog.setContentView(view);
updateDialog.show();
DataLogUtils.uploadUpgradeLog(mContext, "notice"); //上传更新通知弹窗数据
}
private void showDownloadDialog(String md5) {
if (NetworkUtils.isMobileConnected(mContext)) {
Utils.toast(mContext, "当前使用移动数据进行下载");
}
downloadDialog = new Dialog(mContext);
Window window = downloadDialog.getWindow();
if (window != null) {
window.setBackgroundDrawableResource(android.R.color.transparent);
}
View view = View.inflate(mContext, R.layout.app_updating_dialog, null);
app_pb_progress = view.findViewById(R.id.progress);
appProgressSize = view.findViewById(R.id.size);
appProgressRemain = view.findViewById(R.id.remain);
appProgressAnchor = view.findViewById(R.id.progress_anchor);
appProgressPercent = view.findViewById(R.id.percent);
appProgressFilling = view.findViewById(R.id.progress_filling);
view.findViewById(R.id.app_tv_cancel).setOnClickListener(v -> {
DownloadManager.getInstance(mContext).cancel(appEntity.getUrl());
if (appEntity.isForce()) {
AppManager.getInstance().finishAllActivity();
} else {
downloadDialog.dismiss();
}
});
downloadDialog.setOnDismissListener(dialog -> {
DownloadManager.getInstance(mContext).removeObserver(dataWatcher);
isShowDownload = false;
});
int dialogWidth = mContext.getResources().getDisplayMetrics().widthPixels - DisplayUtils.dip2px(60);
downloadDialog.setCanceledOnTouchOutside(false);
downloadDialog.setCancelable(false);
downloadDialog.closeOptionsMenu();
downloadDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
downloadDialog.setContentView(view, new ViewGroup.LayoutParams(dialogWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
downloadDialog.show();
isShowDownload = true;
DownloadManager.getInstance(mContext).addObserver(dataWatcher);
// 添加到下载列表
String path = FileUtils.getDownloadPath(mContext, "光环助手V" + appEntity.getVersion() + "_" + md5 + ".apk");
File file = new File(path);
if (file.exists() && file.delete()) {
Utils.log(file.getName() + " file delete success.");
}
DownloadEntity downloadEntity = new DownloadEntity();
downloadEntity.setUrl(appEntity.getUrl());
downloadEntity.setName("光环助手V" + appEntity.getVersion());
downloadEntity.setPath(path);
downloadEntity.setPlatform("官方版");
downloadEntity.setPackageName(mContext.getPackageName());
DownloadManager.getInstance(mContext).cancel(downloadEntity.getUrl(), false, true);
DownloadManager.getInstance(mContext).pauseAll();
DownloadManager.getInstance(mContext).add(downloadEntity);
}
private String getUpdateOnceOnlySpKey() {
return "UPDATE_ONCE_ONLY_KEY" + PackageUtils.getVersionCode();
}
private String getUpdateOnceOnlySecondSpKey() {
return "UPDATE_ONCE_ONLY_SECOND_KEY" + PackageUtils.getVersionCode();
}
}