Files
assistant-android/app/src/main/java/com/gh/gamecenter/MainActivity.java
juntao dafaeef184 Merge remote-tracking branch 'origin/release' into dev
# Conflicts:
#	app/src/main/java/com/gh/gamecenter/MainActivity.java
#	app/src/main/java/com/halo/assistant/fragment/SettingsFragment.kt
#	dependencies.gradle
2022-05-17 17:10:54 +08:00

1054 lines
46 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;
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.common.util.LoginHelper.WEIBO_SCOPE;
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;
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.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
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.history.HistoryDatabase;
import com.gh.common.history.HistoryHelper;
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.DialogHelper;
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.QuickLoginHelper;
import com.gh.common.util.SPUtils;
import com.gh.common.util.SentryHelper;
import com.gh.common.util.ShareUtils;
import com.gh.common.util.ToastUtils;
import com.gh.common.util.UrlFilterUtils;
import com.gh.common.util.WechatBindHelper;
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.retrofit.BiResponse;
import com.gh.gamecenter.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.gh.gamecenter.room.AppDatabase;
import com.gh.gamecenter.room.dao.SimulatorGameDao;
import com.gh.gamecenter.suggest.SuggestSelectFragment;
import com.gh.gamecenter.suggest.SuggestType;
import com.google.android.exoplayer2.upstream.cache.Cache;
import com.google.gson.JsonSyntaxException;
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 com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.openapi.IWBAPI;
import com.sina.weibo.sdk.openapi.WBAPIFactory;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
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;
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;
HaloApp.getInstance().initFresco();
super.onCreate(savedInstanceState);
setStatusBarColor(Color.TRANSPARENT);
Fragment fragmentFromFM = getSupportFragmentManager().findFragmentById(R.id.layout_activity_content);
mMainWrapperFragment = fragmentFromFM != null ? (MainWrapperFragment) fragmentFromFM : 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.getGhVersionName(), true);
if (isNewFirstLaunch) {
final LunchType lunchType = DeviceTokenUtils.getLaunchType(false);
// 延时两秒提交,避免提交时还没获取到 GID/OAID
AppExecutor.getUiExecutor().executeWithDelay(() -> {
if (!this.isFinishing()) {
LogUtils.uploadDevice(lunchType);
ActivationHelper.sendActivationInfo();
// 第一次打开App删除模拟器游戏记录不包括更新版本
if (HaloApp.getInstance().isBrandNewInstall) {
getTeenagerMode();
SimulatorGameManager.deleteAllSimulatorGame();
}
}
}, 2000L);
getPluginUpdate();
mSp.edit().putBoolean("isNewFirstLaunchV" + PackageUtils.getGhVersionName(), false).apply();
// 记录曾安装过的版本 + 渠道
SPUtils.setString("installedVersionV" + PackageUtils.getGhVersionName(), HaloApp.getInstance().getChannel());
SPUtils.setString(Constants.SP_INSTALL_TYPE, lunchType.name());
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));
// 被改过的包闪退时增加跳转到光环游戏详情并自动下载的方法
if (Config.DEFAULT_CHANNEL_FOR_RELEASE.equals(HaloApp.getInstance().getChannel())) {
DialogHelper.showCenterWarningDialog(this, "发生闪退", "光环助手发生了闪退,建议安装到最新版本修复异常"
, "马上反馈", "马上安装修复",
() -> {
DirectUtils.directToGameDetail(this, Constants.GHZS_GAME_ID, "crash", true, "desc", null);
return null;
},
() -> {
DirectUtils.directToSuggestion(MainActivity.this, SuggestType.crash, "APP闪退", 100);
MtaHelper.onEventWithBasicDeviceInfo(
"闪退弹窗",
"玩家操作", "点击反馈");
return null;
});
} else {
DialogHelper.showCenterWarningDialog(this, "发生闪退", "光环助手刚刚发生了闪退,马上反馈以帮助我们更好地修复问题?(只需简单描述你刚才的操作)"
, "暂不", "马上反馈",
() -> {
DirectUtils.directToSuggestion(MainActivity.this, SuggestType.crash, "APP闪退", 100);
MtaHelper.onEventWithBasicDeviceInfo(
"闪退弹窗",
"玩家操作", "点击反馈");
return null;
},
() -> {
MtaHelper.onEventWithBasicDeviceInfo(
"闪退弹窗",
"玩家操作", "点击关闭");
return null;
});
}
}
// checkTinkerPath(); // 看情况是否需要显示补丁弹窗
// 必须放在这里,否则会导致获取 baseActivity 不是本应用包名
DownloadManager.getInstance().initDownloadService();
ReservationRepository.refreshReservations();
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();
}
// 耗时操作
AppExecutor.getIoExecutor().execute(() -> {
// 上传数据
DataCollectionManager.getInstance().upload();
// 获取默认配置
if (Config.getSettings() == null) {
Config.getGhzsSettings();
}
// 初始化PlatformUtils
PlatformUtils.getInstance(getApplicationContext());
HomePluggableHelper.activationFilterData();
});
//启动app删除视频缓存文件
AppExecutor.getIoExecutor().execute(() -> {
try {
String dirPath = getCacheDir().getAbsolutePath() + File.separator + "exo";
FileUtils.deleteFolder(new File(dirPath));
} catch (Exception e) {
e.printStackTrace();
}
});
//恢复视频流非Wifi提醒
SPUtils.setBoolean(Constants.SP_NON_WIFI_TIPS, true);
//重置首页视频播放进度
SPUtils.setString(Constants.SP_HOME_VIDEO_PLAY_RECORD, "");
postAttentionVideoRecord();
deleteSimulatorGame();
// 检查是否需要触发 XAPK 安装
AppExecutor.getUiExecutor().executeWithDelay(this::resumeXapkInstallIfNeeded, 150);
QuickLoginHelper.getPhoneInfo(this);
WechatBindHelper.getWechatConfig(null);
initWBSDK();
}
@SuppressLint("CheckResult")
private void getTeenagerMode() {
RetrofitManager.getInstance()
.getApi().getTeenagerMode(HaloApp.getInstance().getGid())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BiResponse<ResponseBody>() {
@Override
public void onSuccess(ResponseBody data) {
try {
boolean preStatus = SPUtils.getBoolean(Constants.SP_TEENAGER_MODE);
JSONObject object = new JSONObject(data.string());
boolean curStatus = "open".equals(object.getString("status"));
SPUtils.setBoolean(Constants.SP_TEENAGER_MODE, curStatus);
if (preStatus != curStatus) {
Intent intent = getMainIntent(MainActivity.this);
intent.putExtra(SHOW_AD, true);
finish();
startActivity(intent);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
});
}
//上传关注视频浏览记录
@SuppressLint("CheckResult")
private void postAttentionVideoRecord() {
if (UserManager.getInstance().isLoggedIn()) {
Map<String, Object> requestMap = new HashMap<>();
HistoryDatabase.Companion.getInstance().videoHistoryDao()
.getAttentionVideoRecord()
.flatMap((Function<List<String>, SingleSource<ResponseBody>>) strings -> {
requestMap.put("cache_video_ids", strings);
RequestBody body = ExtensionsKt.toRequestBody(requestMap);
return RetrofitManager.getInstance()
.getApi()
.postAttentionVideoRecord(UserManager.getInstance().getUserId(), body);
})
.subscribeOn(Schedulers.io())
.subscribe(new BiResponse<ResponseBody>() {
@Override
public void onSuccess(ResponseBody data) {
HistoryHelper.deleteAttentionVideoRecord();
}
});
}
}
//查询到模拟器游戏表中逻辑删除的数据后,删除服务器中的记录
@SuppressLint("CheckResult")
private void deleteSimulatorGame() {
SimulatorGameDao dao = AppDatabase.getInstance().simulatorGameDao();
dao.getSimulatorGameByDeleted()
.subscribeOn(Schedulers.io())
.subscribe(new BiResponse<List<String>>() {
@Override
public void onSuccess(List<String> data) {
if (!data.isEmpty()) {
SimulatorGameManager.deleteSimulatorGames(data, () -> {
for (String id : data) {
dao.deleteSimulatorGameById(id);
}
return null;
});
}
}
});
}
@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 = "您也可以联系客服进一步描述闪退的情况,如果您反馈的是新问题,即有机会获得红包奖励";
DialogHelper.showCenterWarningDialog(MainActivity.this, "反馈成功", Html.fromHtml(str.substring(0, str.indexOf("红包奖励")) + "<font color='#FF0000'>红包奖励</font>"), "暂不", "联系客服",
() -> {
if (ShareUtils.isQQClientAvailable(this)) {
DirectUtils.directToQqConversation(this, null);
} else {
toast("本机未安装QQ应用");
}
return null;
}, () -> 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().execute(() -> {
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);
View view = findViewById(R.id.maskContainer);
if (view != null) {
view.setVisibility(View.GONE);
ExtensionsKt.removeFromParent(view);
}
checkDialog();
}
}
private void checkDialog() {
// 检查通知权限
checkNotificationPermission();
// 检查助手更新
AppExecutor.getIoExecutor().execute(() -> {
UpdateManager updateManager = UpdateManager.getInstance(this);
updateManager.checkUpdate(true, null);
updateManager.setDismissCallback(mMainWrapperFragment::getDialog);
});
}
private void showAd(StartupAdEntity ad) {
TextView adContentTv = findViewById(R.id.adContentTv);
View containerView = findViewById(R.id.maskContainer);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
containerView.setElevation(500F);
}
containerView.setOnClickListener(v -> {
// do nothing 只是为了点击拦截事件,避免传递到下面的页面
});
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);
try {
GameEntity gameEntity = GsonUtils.getGson().fromJson(json, new TypeToken<GameEntity>() {
}.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);
}
} catch (JsonSyntaxException exception) {
exception.printStackTrace();
toast("模拟器游戏启动失败,请联系客服反馈相关信息");
SentryHelper.INSTANCE.onEvent(
"SIMULATOR_SHORTCUT_LAUNCH_ERROR",
"raw_json",
json
);
}
break;
case KEY_MARKET_DETAILS:
redirectGameDetail(bundle.getString(KEY_DATA));
break;
}
}
}
Utils.log(bundle);
if (bundle.getInt(EntranceUtils.KEY_POSITION) != -1) {
EventBus.getDefault().post(new EBSkip(MainActivity.EB_SKIP_MAIN, bundle.getInt(EntranceUtils.KEY_POSITION)));
}
}
}, 500);
}
/**
* 应用跳转
*/
private void redirectGameDetail(String packageName) {
String filterQuery = UrlFilterUtils.getFilterQuery("package", packageName, "type", "package_redirect");
RetrofitManager.getInstance().getApi().loadGameDataByPackageName(filterQuery)
.compose(observableToMain())
.subscribe(new Response<List<GameEntity>>() {
@Override
public void onResponse(@Nullable List<GameEntity> 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), "应用跳转", null);
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<Integer, Boolean>() {
@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().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;
DialogHelper.showCenterWarningDialog(this,
"提示", msg,
"直接退出",
"立即安装",
() -> {
handler.postDelayed(() -> PackageInstaller.install(MainActivity.this, finalDownloadEntity), 200);
return null;
},
() -> {
finish();
return null;
});
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().statClickData();
super.finish();
}
@Override
protected void onSaveInstanceState(@NotNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(CURRENT_PAGE, mMainWrapperFragment.getCurrentItem());
if (mMainWrapperFragment != null) {
outState.putInt(BaseFragment_ViewPager.ARGS_INDEX, mMainWrapperFragment.getCurrentItem());
}
}
@Override
protected boolean preventRecreateFragmentByFragmentManager() {
return true;
}
@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_VIDEO, false)) {
mMainWrapperFragment.setCurrentItem(2);
}
}
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<HashMap<String, Set<String>>>() {
// }.getType();
//
// final Map<String, Set<String>> tinkerIdMap;
// final String tinkerMapJson = mSp.getString(Config.PATCHES, "");
// if (!TextUtils.isEmpty(tinkerMapJson)) {
// tinkerIdMap = gson.fromJson(tinkerMapJson, type);
// } else {
// tinkerIdMap = new HashMap<>();
// }
//
// Set<String> 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().getApi().checkDevice(body)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Response<ResponseBody>() {
@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 BufferedReader reader = new BufferedReader(new InputStreamReader(in));
InnerMetaInfoEntity info = GsonUtils.getGson().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_BBS));
} 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();
deleteSimulatorGame();
}
}
// 接收登录和登出更新事件统计的 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
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);
}
//需要提前初始化微博sdk否则第一次分享或授权登录会失败
private void initWBSDK() {
try {
IWBAPI mWBAPI = WBAPIFactory.createWBAPI(this);
mWBAPI.registerApp(this, new AuthInfo(this, Config.WEIBO_APPKEY, "http://www.sina.com", WEIBO_SCOPE));
} catch (Throwable e) {
// 微博 SDK 缺少 x86 的 so
// 所以 x86 的 AS 模拟器/ Genymotion 会初始化失败,但实测部分硬性需要提供 x86 SO 的模拟器 (如雷电) 却又能正常使用
// 这里加个简单日志,看看到底有没有(有多少)真实设备出现初始化失败的问题
if (!BuildConfig.DEBUG) {
SPUtils.setBoolean(Constants.SP_USER_NEED_WEIBO_X86_SO, true);
e.printStackTrace();
}
}
}
/**
* 重新触发 XAPK 安装流程
* 因为 Android 12 起授予应用安装未知应用权限以后不触发进程重启,导致应用一直无法读写 android/data 目录
* 所以这里再手动重启应用进程时再触发一回安装
*/
private void resumeXapkInstallIfNeeded() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
String xapkUrl = SPUtils.getString(Constants.SP_XAPK_URL);
if (!TextUtils.isEmpty(xapkUrl)) {
DownloadEntity downloadEntity = DownloadManager.getInstance().getDownloadEntityByUrl(xapkUrl);
if (downloadEntity != null) {
PackageInstaller.install(this, downloadEntity, false);
}
}
SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, "");
SPUtils.setString(Constants.SP_XAPK_URL, "");
}
}
@Override
protected boolean isAutoResetViewBackgroundEnabled() {
return true;
}
}