package com.gh.gamecenter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import com.gh.base.AppUncaughtHandler;
import com.gh.base.BaseActivity;
import com.gh.base.fragment.BaseFragment_ViewPager;
import com.gh.common.AppExecutor;
import com.gh.common.DefaultUrlHandler;
import com.gh.common.avoidcallback.AvoidOnResultManager;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.common.exposure.meta.MetaUtil;
import com.gh.common.repository.ReservationRepository;
import com.gh.common.simulator.SimulatorGameManager;
import com.gh.common.util.ActivationHelper;
import com.gh.common.util.AdHelper;
import com.gh.common.util.ClassUtils;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DeviceTokenUtils;
import com.gh.common.util.DeviceUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DirectUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.EntranceUtils;
import com.gh.common.util.ErrorHelper;
import com.gh.common.util.ExtensionsKt;
import com.gh.common.util.GsonUtils;
import com.gh.common.util.HomePluggableHelper;
import com.gh.common.util.LogUtils;
import com.gh.common.util.LunchType;
import com.gh.common.util.MtaHelper;
import com.gh.common.util.NotificationHelper;
import com.gh.common.util.PackageInstaller;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.PlatformUtils;
import com.gh.common.util.SPUtils;
import com.gh.common.util.ShareUtils;
import com.gh.common.util.ToastUtils;
import com.gh.common.util.UrlFilterUtils;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.download.DownloadFragment;
import com.gh.gamecenter.entity.CommunityEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.entity.InnerMetaInfoEntity;
import com.gh.gamecenter.entity.NotificationUgc;
import com.gh.gamecenter.entity.StartupAdEntity;
import com.gh.gamecenter.eventbus.EBNetworkState;
import com.gh.gamecenter.eventbus.EBReuse;
import com.gh.gamecenter.eventbus.EBSkip;
import com.gh.gamecenter.fragment.MainWrapperFragment;
import com.gh.gamecenter.home.skip.PackageSkipActivity;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.UpdateManager;
import com.gh.gamecenter.manager.UserManager;
import com.gh.gamecenter.normal.NormalFragment;
import com.gh.gamecenter.packagehelper.PackageViewModel;
import com.gh.gamecenter.qa.CommunityFragment;
import com.gh.gamecenter.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.gh.gamecenter.suggest.SuggestSelectFragment;
import com.gh.gamecenter.suggest.SuggestType;
import com.google.android.exoplayer2.upstream.cache.Cache;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.halo.assistant.HaloApp;
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 org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import kotlin.jvm.functions.Function1;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.HttpException;
import tv.danmaku.ijk.media.exo2.ExoSourceManager;
import static com.gh.common.util.EntranceUtils.ENTRANCE_BROWSER;
import static com.gh.common.util.EntranceUtils.HOST_LAUNCH_SIMULATOR_GAME;
import static com.gh.common.util.EntranceUtils.HOST_QQ;
import static com.gh.common.util.EntranceUtils.HOST_QQ_GROUP;
import static com.gh.common.util.EntranceUtils.HOST_WEB;
import static com.gh.common.util.EntranceUtils.KEY_DATA;
import static com.gh.common.util.EntranceUtils.KEY_MARKET_DETAILS;
import static com.gh.common.util.EntranceUtils.KEY_NEXT_TO;
import static com.gh.common.util.EntranceUtils.KEY_TO;
import static com.gh.common.util.EntranceUtils.KEY_TYPE;
import static com.gh.common.util.ExtensionsKt.observableToMain;
import static com.gh.gamecenter.fragment.MainWrapperFragment.INDEX_PERSONAL;
import static com.gh.gamecenter.personal.PersonalFragment.LOGIN_TAG;
import static com.gh.gamecenter.personal.PersonalFragment.LOGOUT_TAG;
public class MainActivity extends BaseActivity {
public final static String EB_SKIP_MAIN = "MainActivity";
public final static String SWITCH_TO_COMMUNITY = "switch_to_community";
public final static String SWITCH_TO_VIDEO = "switch_to_video";
public final static String SHOW_AD = "show_ad";
private final static String CURRENT_PAGE = "current_page";
private PackageViewModel mPackageViewModel;
private MainWrapperFragment mMainWrapperFragment;
private SharedPreferences mSp;
// 黄壮华 按连续按返回键两次才退出应用
private long[] mHits = new long[2];
public static boolean isNewFirstLaunch;
private Handler handler = new Handler();
public boolean showAd = false; // 是否显示广告
@Override
protected void onCreate(Bundle savedInstanceState) {
showAd = getIntent().getBooleanExtra(SHOW_AD, false) && savedInstanceState == null;
super.onCreate(savedInstanceState);
setStatusBarColor(Color.TRANSPARENT);
mMainWrapperFragment = new MainWrapperFragment();
if (savedInstanceState != null) {
mMainWrapperFragment.setArguments(savedInstanceState);
} else if (getIntent() != null) {
mMainWrapperFragment.setArguments(getIntent().getExtras());
}
replaceFragment(mMainWrapperFragment);
mSp = PreferenceManager.getDefaultSharedPreferences(this);
isNewFirstLaunch = mSp.getBoolean("isNewFirstLaunchV" + PackageUtils.getVersionName(), true);
if (isNewFirstLaunch) {
final LunchType lunchType = DeviceTokenUtils.getLaunchType();
// 延时两秒提交,避免提交时还没获取到 GID/OAID
AppExecutor.getUiExecutor().executeWithDelay(() -> {
if (!this.isFinishing()) {
LogUtils.uploadDevice(lunchType);
ActivationHelper.sendActivationInfo();
// 第一次打开App删除模拟器游戏记录(不包括更新版本)
if (HaloApp.getInstance().isBrandNewInstall) {
SimulatorGameManager.deleteAllSimulatorGame();
}
}
}, 2000L);
getPluginUpdate();
mSp.edit().putBoolean("isNewFirstLaunchV" + PackageUtils.getVersionName(), false).apply();
checkDevice(); // 根据设备信息判断用户是否是新用户
}
// 若 SplashActivity 没能获取到 Gid 这里再重试一次
if (TextUtils.isEmpty(HaloApp.getInstance().getGid())) {
DataUtils.getGid();
}
mPackageViewModel = ViewModelProviders.of(this, new PackageViewModel.Factory()).get(PackageViewModel.class);
final String message = Config.getExceptionMsg();
if (!TextUtils.isEmpty(message)) {
Config.setExceptionMsg(null);
AppUncaughtHandler.reportException(this, new Throwable(message));
DialogUtils.showWarningDialog(this, "发生闪退", "光环助手刚刚发生了闪退,马上反馈以帮助我们更好地修复问题?(只需简单描述你刚才的操作)"
, "暂不", "马上反馈",
() -> {
startActivityForResult(SuggestionActivity.getIntent(MainActivity.this, SuggestType.crash, "APP闪退:"), 100);
MtaHelper.onEventWithBasicDeviceInfo(
"闪退弹窗",
"玩家操作", "点击反馈");
},
() -> MtaHelper.onEventWithBasicDeviceInfo(
"闪退弹窗",
"玩家操作", "点击关闭"));
}
// checkTinkerPath(); // 看情况是否需要显示补丁弹窗
// 必须放在这里,否则会导致获取 baseActivity 不是本应用包名
DownloadManager.getInstance(this).initDownloadService();
ReservationRepository.refreshReservations();
if (getIntent().getBooleanExtra(SWITCH_TO_COMMUNITY, false)) {
handler.postDelayed(this::switchToCommunityTabAndRefresh, 800);
}
if (getIntent().getBooleanExtra(SWITCH_TO_VIDEO, false)) {
handler.postDelayed(() -> mMainWrapperFragment.setCurrentItem(2), 800);
}
// 跳转至其它页面
if (getIntent() != null
&& getIntent().getExtras() != null
&& getIntent().getBooleanExtra(EntranceUtils.KEY_REQUIRE_REDIRECT, false)) {
doSkip();
}
if (BuildConfig.DEBUG) {
handler.postDelayed(() -> {
EntranceUtils.jumpShortcut(this);
}, 500);
}
if (showAd) {
observeAd();
} else {
checkDialog();
}
// handler.postDelayed(() -> {
// PushHelper.postPushClickAction(this.getApplicationContext(), null);
// }, 2000);
// 耗时操作
AppExecutor.getIoExecutor().execute(() -> {
// 上传数据
DataCollectionManager.getInstance(getApplicationContext()).upload();
// 获取默认配置
Config.getGhzsSettings();
// 初始化PlatformUtils
PlatformUtils.getInstance(getApplicationContext());
// // 友盟记录启动
// PushAgent.getInstance(this).onAppStart();
HomePluggableHelper.activationFilterData();
});
//启动app删除视频缓存文件
AppExecutor.getIoExecutor().execute(() -> {
try {
String dirPath = getCacheDir().getAbsolutePath() + File.separator + "exo";
FileUtils.deleteFolder(new File(dirPath));
} catch (Exception e) {
e.printStackTrace();
}
});
//恢复顶部视频默认静音状态
SPUtils.setBoolean(Constants.SP_TOP_VIDEO_VOICE, true);
//恢复视频流非Wifi提醒
SPUtils.setBoolean(Constants.SP_NON_WIFI_TIPS, true);
//重置首页视频播放进度
SPUtils.setString(Constants.SP_HOME_VIDEO_PLAY_RECORD, "");
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
int currentPageIndex = savedInstanceState.getInt(CURRENT_PAGE, -1);
if (currentPageIndex >= 0) {
EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, currentPageIndex));
if (currentPageIndex == MainWrapperFragment.INDEX_VIDEO) {
DisplayUtils.setLightStatusBar(this, false);
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == SuggestSelectFragment.SUGGEST_TYPE_REQUEST) {
showKefuReportDialog();
}
}
private void showKefuReportDialog() {
// 只有是APP闪退反馈成功后弹出联系客服的弹窗
String str = "您也可以联系客服进一步描述闪退的情况,如果您反馈的是新问题,即有机会获得红包奖励";
DialogUtils.showWarningDialog(MainActivity.this, "反馈成功", Html.fromHtml(str.substring(0, str.indexOf("红包奖励")) + "红包奖励"), "暂不", "联系客服",
() -> {
if (ShareUtils.isQQClientAvailable(this)) {
DirectUtils.directToQqConversation(this, null);
} else {
toast("本机未安装QQ应用");
}
}, null);
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
releaseExoSourceCache();
}
/**
* 由于ExoTransformer中拦截了{@link ExoSourceManager#release}方法,
* 所以需要在app退出的时候手动release
*/
private void releaseExoSourceCache() {
Cache cache = ExoSourceManager.getCacheSingleInstance(HaloApp.getInstance().getApplication(), null);
cache.release();
try {
Field cacheField = ExoSourceManager.class.getDeclaredField("mCache");
cacheField.setAccessible(true);
cacheField.set(null, null);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private void observeAd() {
AdHelper.startupAd.observe(this, startupAdEntity -> {
if (showAd) {
if (startupAdEntity == null) {
hideAd(true);
} else {
showAd(startupAdEntity);
AppExecutor.getUiExecutor().executeWithDelay(() -> hideAd(true), 2000);
}
}
});
AppExecutor.getUiExecutor().executeWithDelay(() -> hideAd(false), 950);
}
private void hideAd(boolean forceToHide) {
if (forceToHide
|| AdHelper.startupAd.getValue() == null) {
showAd = false;
getIntent().putExtra(SHOW_AD, false);
findViewById(R.id.maskContainer).setVisibility(View.GONE);
mMainWrapperFragment.getWelcomeDialog();
checkDialog();
}
}
private void checkDialog() {
// 检查通知权限
checkNotificationPermission();
// 检查助手更新
AppExecutor.getIoExecutor().execute(() -> {
UpdateManager.getInstance(this).checkUpdate(true, null);
});
}
private void showAd(StartupAdEntity ad) {
TextView adContentTv = findViewById(R.id.adContentTv);
adContentTv.setText(ad.getDesc());
adContentTv.setVisibility(View.VISIBLE);
if (ad.getButton()) {
View btn = findViewById(R.id.adBtn);
btn.setOnClickListener((v) -> {
DirectUtils.directToLinkPage(this, ad.getJump(), "(启动广告)", "");
LogUtils.logStartAd("click_watch_start_ads", ad);
});
btn.setVisibility(View.VISIBLE);
LogUtils.logStartAd("watch_start_ads", ad);
} else {
LogUtils.logStartAd("start_ads", ad);
}
}
@NonNull
public static Intent getMainIntent(Context context) {
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
private void doSkip() {
if (getIntent() != null && getIntent().getExtras() != null) {
getIntent().getExtras().putBoolean(EntranceUtils.KEY_REQUIRE_REDIRECT, false);
}
handler.postDelayed(() -> {
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String to = bundle.getString(KEY_TO);
if (!TextUtils.isEmpty(to)) {
Class> clazz = ClassUtils.forName(to);
if (clazz != null) {
String entrance = bundle.getString(EntranceUtils.KEY_ENTRANCE);
if (TextUtils.isEmpty(entrance) || !entrance.startsWith("(") || !entrance.endsWith(")")) {
bundle.putString(EntranceUtils.KEY_ENTRANCE, "(插件跳转)");
}
String packageName = bundle.getString("packageName");
if (packageName != null) {
bundle.putInt(BaseFragment_ViewPager.ARGS_INDEX, 1);
}
if (NormalFragment.class.isAssignableFrom(clazz)) {
NormalActivity.startFragment(MainActivity.this, (Class extends NormalFragment>) clazz, bundle);
} else {
Intent skipIntent = new Intent(MainActivity.this, clazz);
skipIntent.putExtras(bundle);
// startActivity(skipIntent);
AvoidOnResultManager.Companion.getInstance(this)
.startForResult(skipIntent, (resultCode, data) -> {
Bundle nextToBundle = getIntent().getBundleExtra(KEY_NEXT_TO);
if (nextToBundle != null) {
EntranceUtils.jumpActivity(this, nextToBundle);
}
});
}
} else {
// 使用光环进行二次跳转的页面会经过这里
switch (to) {
case HOST_QQ:
DirectUtils.directToQqConversation(this, bundle.getString(KEY_DATA));
break;
case HOST_QQ_GROUP:
DirectUtils.directToQqGroup(this, bundle.getString(KEY_DATA));
break;
case HOST_WEB:
String url = bundle.getString(KEY_DATA) == null ? "" : bundle.getString(KEY_DATA);
if ("internal".equals(bundle.getString(KEY_TYPE))) {
DirectUtils.directToWebView(this, url, ENTRANCE_BROWSER);
} else {
DirectUtils.directToExternalBrowser(this, url);
}
break;
case HOST_LAUNCH_SIMULATOR_GAME:
String json = getIntent().getStringExtra(EntranceUtils.KEY_GAME);
GameEntity gameEntity = GsonUtils.getGson().fromJson(json, new TypeToken() {
}.getType());
DownloadEntity downloadEntity = SimulatorGameManager.findDownloadEntityByUrl(gameEntity.getApk().get(0).getUrl());
if (downloadEntity != null) {
File file = new File(downloadEntity.getPath());
if (!file.exists()) {
ToastUtils.INSTANCE.showToast("文件已被删除,无法启动");
return;
}
SimulatorGameManager.launchSimulatorGame(downloadEntity, gameEntity);
}
break;
case KEY_MARKET_DETAILS:
redirectGameDetail(bundle.getString(KEY_DATA));
break;
}
}
}
Utils.log(bundle);
if (bundle.getInt(EntranceUtils.KEY_POSITION) != -1) {
Utils.log("abc");
EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, bundle.getInt(EntranceUtils.KEY_POSITION)));
}
}
}, 500);
}
/**
* 应用跳转
*
* @param packageName
*/
private void redirectGameDetail(String packageName) {
String filterQuery = UrlFilterUtils.getFilterQuery("package", packageName, "type", "package_redirect");
RetrofitManager.getInstance(this).getApi().loadGameDataByPackageName(filterQuery)
.compose(observableToMain())
.subscribe(new Response>() {
@Override
public void onResponse(@Nullable List response) {
super.onResponse(response);
if (response == null || response.isEmpty()) return;
if (response.size() > 1) {
startActivity(PackageSkipActivity.getIntent(MainActivity.this, response));
LogUtils.uploadPackageSkip("external_jump", "进入展示页", "", "");
} else {
GameDetailActivity.startGameDetailActivity(MainActivity.this, response.get(0), "应用跳转");
LogUtils.uploadPackageSkip("external_jump", "进入游戏详情", response.get(0).getId(), response.get(0).getName());
}
}
@Override
public void onFailure(@Nullable HttpException e) {
super.onFailure(e);
try {
ErrorHelper.handleErrorWithCustomizedHandler(MainActivity.this, e.response().errorBody().string(), false, new Function1() {
@Override
public Boolean invoke(Integer code) {
if (code == 404001) {
if (showAd) {
AppExecutor.getUiExecutor().executeWithDelay(() -> {
toast("抱歉,暂未找到相关内容");
}, 1000);
} else {
toast("抱歉,暂未找到相关内容");
}
LogUtils.uploadPackageSkip("external_jump", "进入游戏库", "", "");
EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, MainWrapperFragment.INDEX_GAME));
return true;
}
return false;
}
});
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
private void checkNotificationPermission() {
// 仅登录后再启动光环时请求一次权限
if (UserManager.getInstance().isLoggedIn()) {
NotificationHelper.showNotificationHintDialog(NotificationUgc.LOGIN, null);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 && !mMainWrapperFragment.onHandleBackPressed()) {
DownloadEntity downloadEntity = null;
for (DownloadEntity entity : DownloadManager.getInstance(getApplicationContext()).getAllDownloadEntityExcludeSilentUpdate()) {
if (entity.getStatus().equals(DownloadStatus.done)) {
if (PackageUtils.isInstalled(getApplicationContext(), entity.getPackageName())
&& (!entity.isPlugin()
|| PackageUtils.isSignedByGh(getApplicationContext(), entity.getPackageName()))) {
continue;
}
if (ExtensionsKt.isSimulatorGame(entity)) continue;
if (downloadEntity == null) {
downloadEntity = entity;
} else if (entity.getEnd() > downloadEntity.getEnd()) {
downloadEntity = entity;
}
}
}
if (downloadEntity != null) {
String msg;
if (downloadEntity.isPlugin()) {
msg = "《" + downloadEntity.getName() + "-"
+ PlatformUtils.getInstance(getApplicationContext()).getPlatformName(downloadEntity.getPlatform())
+ "》已下载完但还未安装,是否立即安装?";
} else {
msg = "《" + downloadEntity.getName() + "》已下载完但还未安装,是否立即安装?";
}
DownloadEntity finalDownloadEntity = downloadEntity;
DialogUtils.showWarningDialog(this,
"提示", msg,
"直接退出",
"立即安装",
() -> handler.postDelayed(() -> PackageInstaller.install(MainActivity.this, finalDownloadEntity), 200),
this::finish);
return true;
}
System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
mHits[mHits.length - 1] = SystemClock.uptimeMillis();
if (mHits[0] >= (SystemClock.uptimeMillis() - 1000)) {
finish();
} else {
toast("再按一次就退出光环助手了哦");
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
protected boolean handleBackPressed() {
return true;
}
@Override
public void finish() {
// 上传数据
DataCollectionManager.getInstance(getApplicationContext()).statClickData();
super.finish();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(CURRENT_PAGE, mMainWrapperFragment.getCurrentItem());
if (mMainWrapperFragment != null) {
outState.putInt(BaseFragment_ViewPager.ARGS_INDEX, mMainWrapperFragment.getCurrentItem());
}
}
@Override
protected int getLayoutId() {
if (showAd) {
return R.layout.activity_main;
} else {
return R.layout.layout_wrapper_activity;
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// 跳转至其它页面
if (getIntent() != null
&& getIntent().getExtras() != null
&& getIntent().getBooleanExtra(EntranceUtils.KEY_REQUIRE_REDIRECT, false)) {
doSkip();
}
// 跳转到问答社区并刷新
if (getIntent().getBooleanExtra(SWITCH_TO_COMMUNITY, false)) {
switchToCommunityTabAndRefresh();
}
if (getIntent().getBooleanExtra(SWITCH_TO_VIDEO, false)) {
mMainWrapperFragment.setCurrentItem(2);
}
}
private void switchToCommunityTabAndRefresh() {
getIntent().putExtra(SWITCH_TO_COMMUNITY, false);
Log.e("Switch", "true");
EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, MainWrapperFragment.INDEX_ASK));
EventBus.getDefault().post(new EBReuse(CommunityFragment.EB_RETRY_PAGE));
}
private void checkTinkerPath() {
// CommonDebug.logMethodWithParams(this, TinkerManager.getTinkerId(), TinkerManager.getNewTinkerId());
// CommonDebug.logMethodWithParams(this, CrashReport.getAppVer(), CrashReport.getAppID(), CrashReport.getAppChannel(), CrashReport.getSdkExtraData());
//
// // 1.(母包)首次启动,tinkerId不为空,newTinkerId(patchTinkerId)应该是空的
// // 2. 补丁包启动,tinkerId和之前一致,但newTinkerId不一致
// // 2.1 显示更新信息弹窗,记录tinkerId+newTinkerId
// // 2.1.1 若tinkerId一致,但newTinkerId不一致才能认为是一次补丁更新
//
// String tinkerId = TinkerManager.getTinkerId();
// String newTinkerId = TinkerManager.getNewTinkerId();
//
// if (TextUtils.isEmpty(newTinkerId)) {
// //这是一个新的母包,没有任何补丁信息
// return;
// }
//
// final Gson gson = new Gson();
//
// Type type = new TypeToken>>() {
// }.getType();
//
// final Map> tinkerIdMap;
// final String tinkerMapJson = mSp.getString(Config.PATCHES, "");
// if (!TextUtils.isEmpty(tinkerMapJson)) {
// tinkerIdMap = gson.fromJson(tinkerMapJson, type);
// } else {
// tinkerIdMap = new HashMap<>();
// }
//
// Set tinkerIdSet = tinkerIdMap.get(tinkerId);
// if (tinkerIdSet == null) {
// tinkerIdSet = new HashSet<>();
// tinkerIdMap.put(tinkerId, tinkerIdSet);
// }
//
// // 有新的补丁,没有显示过
// if (!tinkerIdSet.contains(newTinkerId)) {
// tinkerIdSet.add(newTinkerId);
//
// final Dialog dialog = new Dialog(this, R.style.GhAlertDialog);
//
// View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_alert, null);
// TextView contentTv = contentView.findViewById(R.id.dialog_content);
// TextView titleTv = contentView.findViewById(R.id.dialog_title);
// TextView negativeTv = contentView.findViewById(R.id.dialog_negative);
// TextView positiveTv = contentView.findViewById(R.id.dialog_positive);
//
// titleTv.setText("补丁更新成功");
// contentTv.setText(("光环助手已成功更新到V" + PackageUtils.getVersionName() + "-" + newTinkerId));
// positiveTv.setText("知道了");
// negativeTv.setText(null);
//
// negativeTv.setOnClickListener(view -> dialog.dismiss());
//
// positiveTv.setOnClickListener(view -> dialog.dismiss());
// dialog.setOnDismissListener(dialog1 -> mSp.edit().putString(Config.PATCHES, gson.toJson(tinkerIdMap)).apply());
//
// dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
// dialog.setContentView(contentView);
// dialog.show();
// }
}
private void checkDevice() {
String content = DeviceUtils.getUserDevice(MainActivity.this).toString();
RequestBody body = RequestBody.create(MediaType.parse("application/json"), content);
RetrofitManager.getInstance(this).getApi().checkDevice(body)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Response() {
@Override
public void onResponse(ResponseBody response) {
super.onResponse(response);
try {
String string = response.string();
JSONObject object = new JSONObject(string);
String deviceId = object.getString("device_id");
if (!TextUtils.isEmpty(deviceId)) {
oldUserSkip(deviceId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void oldUserSkip(String deviceId) {
mSp.edit().putString("syncDeviceID", deviceId).apply();
DialogUtils.showForceDialog(MainActivity.this, "数据同步提醒"
, "系统检测到你是光环助手的老用户,为了避免数据丢失,请尽快登录"
, "前往登录", "残忍拒绝", new DialogUtils.ConfirmListener() {
@Override
public void onConfirm() {
EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, INDEX_PERSONAL));
}
}, null);
}
// 获取META-INF中的plugin_update 文件,判断是否从游戏插件中下载的app,是则获取游戏id,启动游戏更新,下载该游戏
private void getPluginUpdate() {
AppExecutor.getIoExecutor().execute(() -> {
ApplicationInfo appinfo = getApplicationInfo();
String sourceDir = appinfo.sourceDir;
ZipFile zipfile = null;
try {
zipfile = new ZipFile(sourceDir);
Enumeration> entries = zipfile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
String entryName = entry.getName();
if (entryName.contains("gh_assist")) {
String packageName = entryName.substring(entryName.lastIndexOf("_") + 1);
startActivity(DownloadManagerActivity.getDownloadMangerIntent(MainActivity.this,
packageName, DownloadFragment.INDEX_UPDATE, "(游戏插件)"));
break;
} else if (entryName.contains("halo_skip.json")) {
InputStream in = zipfile.getInputStream(entry);
if (in != null) {
final Gson gson = new Gson();
final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
InnerMetaInfoEntity info = gson.fromJson(reader, InnerMetaInfoEntity.class);
if (info != null) {
if (EntranceUtils.HOST_COMMUNITY.equals(info.getType())) {
UserManager.getInstance().setCommunityData(new CommunityEntity(info.getLink(), info.getText()));
runOnUiThread(() -> mMainWrapperFragment.setCurrentItem(MainWrapperFragment.INDEX_ASK));
} else {
DirectUtils.directToSpecificPage(this,
info.getType(),
info.getLink(),
info.getText(),
EntranceUtils.KEY_PLUGIN,
"特定包启动跳转");
}
}
}
} else if (entryName.contains("halo_skip.dat")) {
InputStream in = zipfile.getInputStream(entry);
if (in != null) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String content = "";
for (String line; (line = reader.readLine()) != null; content += line) ;
if (!TextUtils.isEmpty(content)) {
DefaultUrlHandler.interceptUrl(this, content, "(特定包启动跳转)");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (zipfile != null) {
try {
zipfile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
// 连接上网络事件
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(EBNetworkState busNetworkState) {
if (busNetworkState.isNetworkConnected()) {
if (Config.getSettings() == null) {
AppExecutor.getIoExecutor().execute(Config::getGhzsSettings);
}
mPackageViewModel.checkData();
}
}
// 接收登录和登出更新事件统计的 Meta
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(EBReuse reuse) {
if (reuse.getType().equals(LOGIN_TAG) || reuse.getType().equals(LOGOUT_TAG)) {
MetaUtil.INSTANCE.refreshMeta();
}
}
@Override
protected boolean useButterKnife() {
return false;
}
@Override
public String getActivityNameInChinese() {
return "游戏首页";
}
public static void skipToMainActivity(Context context, int position) {
Activity activity = AppManager.getInstance().findActivity(MainActivity.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1
&& activity != null && !activity.isDestroyed()) {
EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, position));
} else {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, position));
}
}, 300);
}
Intent intent = MainActivity.getMainIntent(context);
context.startActivity(intent);
}
}