package com.gh.gamecenter; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import com.g00fy2.versioncompare.Version; import com.gh.base.BaseActivity; import com.gh.common.AppExecutor; import com.gh.common.constant.Config; import com.gh.common.constant.Constants; import com.gh.common.dialog.PrivacyPolicyDialogFragment; import com.gh.common.tracker.TrackerLogger; import com.gh.common.util.AdHelper; import com.gh.common.util.DeviceTokenUtils; import com.gh.common.util.DialogHelper; import com.gh.common.util.DialogUtils; import com.gh.common.util.DisplayUtils; import com.gh.common.util.PackageFlavorHelper; import com.gh.common.util.ExtensionsKt; import com.gh.common.util.GameSubstituteRepositoryHelper; import com.gh.common.util.GsonUtils; import com.gh.common.util.LunchType; import com.gh.common.util.MtaHelper; import com.gh.common.util.PackageUtils; import com.gh.common.util.PlatformUtils; import com.gh.common.util.SPUtils; import com.gh.common.util.SimpleCallback; import com.gh.common.util.TagUtils; import com.gh.common.util.UsageStatsHelper; import com.gh.download.DownloadManager; import com.gh.gamecenter.entity.AuthDialogEntity; import com.gh.gamecenter.entity.DeviceDialogEntity; import com.gh.gamecenter.entity.PrivacyPolicyEntity; import com.gh.gamecenter.retrofit.BiResponse; import com.gh.gamecenter.retrofit.Response; import com.gh.gamecenter.retrofit.RetrofitManager; import com.halo.assistant.HaloApp; import com.lightgame.download.DownloadEntity; import com.lightgame.download.FileUtils; import org.jetbrains.annotations.NotNull; import org.json.JSONObject; import java.io.File; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.UUID; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import okhttp3.RequestBody; import okhttp3.ResponseBody; import pub.devrel.easypermissions.AfterPermissionGranted; import pub.devrel.easypermissions.EasyPermissions; /** * 引导页面 */ public class SplashScreenActivity extends BaseActivity { private SharedPreferences mSharedPreferences; private boolean mIsNewForThisVersion; private boolean mStartMainActivityDirectly = false; // 是否不需要用户点击立即体验就直接跳转首页 private static final int REQUEST_PERMISSION_TAG = 30001; private String[] mPermissions = { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE}; public static Intent getSplashScreenIntent(Context context, Bundle bundle) { Intent intent = new Intent(context, SplashScreenActivity.class); intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtras(bundle); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mIsNewForThisVersion = mSharedPreferences.getBoolean("isNewFirstLaunchV" + PackageUtils.getGhVersionName(), true); HaloApp.getInstance().isNewForThisVersion = mIsNewForThisVersion; // 用户不是新版本,但应用最后更新时间不是上次的时间代表用户重新安装了当前版本 if (!mIsNewForThisVersion) { long ghLastUpdateTime = SPUtils.getLong(Constants.SP_GH_LAST_UPDATE_TIME, 0); if (ghLastUpdateTime != 0 && ghLastUpdateTime != PackageUtils.getHaloLastUpdateTime()) { HaloApp.getInstance().setIsReinstallTheSameVersion(true); } } super.onCreate(savedInstanceState); DisplayUtils.transparentStatusBar(this); TrackerLogger.logAppLaunch(this); // 处理助手已经在后台运行导致的再次启动助手 if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { finish(); return; } // 判断是不是这个版本的新用户 if (mIsNewForThisVersion) { mContentView.setPadding(0, 0, 0, 0); ViewPager guideLayout = findViewById(R.id.splash_intro_vp_guide); guideLayout.setAdapter(new GuidePagerAdapter()); // 判断是不是光环的新用户 if (SPUtils.getBoolean(Constants.SP_BRAND_NEW_USER, true)) { // 引导页需用户点击 “立即体验” 按钮才进入首页,所以这里不能置为true // https://git.ghzs.com/pm/halo-app-issues/-/issues/1422(第3点) // mStartMainActivityDirectly = true; SPUtils.setLong(Constants.SP_INITIAL_USAGE_TIME, System.currentTimeMillis()); HaloApp.getInstance().isBrandNewInstall = true; if (!PackageFlavorHelper.IS_TEST_FLAVOR) { showPrivacyDialog(guideLayout); } else { // Test dex2oat executeDex2OatInAdvance(); DialogHelper.showDialog(this, "选择接口环境", "这个弹窗只会在右上角有环境标签的测试包出现\n进入应用以后还可以到关于我们页面长按应用图标重新选择", "正式环境", "测试环境", () -> { SPUtils.setBoolean(Constants.SP_IS_DEV_ENV, false); showPrivacyDialog(guideLayout); }, () -> { SPUtils.setBoolean(Constants.SP_IS_DEV_ENV, true); showPrivacyDialog(guideLayout); }, false, "", "" ); } } else { cancelPreviousUpdateTask(); guideLayout.setVisibility(View.VISIBLE); // requestPermission(); } } else { launchMainActivity(); } if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) { SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, ""); SPUtils.setString(Constants.SP_XAPK_URL, ""); } } private void showPrivacyDialog(ViewPager guideLayout) { PrivacyPolicyDialogFragment.show(this, null, (isSuccess) -> { if (isSuccess) { showPrivacyPolicy((shouldRequestPermission) -> { // Dialog dismiss 后的回调 guideLayout.setVisibility(View.VISIBLE); SPUtils.setBoolean(Constants.SP_BRAND_NEW_USER, false); if (shouldRequestPermission) { requestPermission(); } else { mStartMainActivityDirectly = false; } }); } else { DialogUtils.showPrivacyPolicyDisallowDialog(this, PrivacyPolicyEntity.createDefaultData(), () -> { showPrivacyDialog(guideLayout); }); } return null; }); } // 删除更新后的光环助手包 private void cancelPreviousUpdateTask() { List all = DownloadManager.getInstance().getAllDownloadEntity(); for (DownloadEntity downloadEntity : all) { if (downloadEntity.getPackageName().equals(getPackageName())) { DownloadManager.getInstance().cancel(downloadEntity.getUrl(), true, true); break; } } } /** * 让系统执行 dex2oat */ private void executeDex2OatInAdvance() { try { Runtime.getRuntime().exec("cmd package compile -m speed -f " + BuildConfig.APPLICATION_ID); } catch (Throwable e) { e.printStackTrace(); } } private void requestPermission() { if (!EasyPermissions.hasPermissions(this, mPermissions)) { checkAndRequestPermission(); } } @SuppressLint("CheckResult") private void deviceDialogSetting() { RetrofitManager.getInstance() .getApi().deviceDialogs() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new BiResponse>() { @Override public void onSuccess(List entities) { if (entities.size() > 0) { SPUtils.setString(Constants.SP_DEVICE_REMIND, GsonUtils.toJson(entities)); } } }); } @SuppressLint("CheckResult") private void getRegulationTestStatus() { RetrofitManager.getInstance() .getApi().getRegulationTestStatus() .subscribe(new BiResponse() { @Override public void onSuccess(ResponseBody data) { try { JSONObject object = new JSONObject(data.string()); SPUtils.setString(Constants.SP_REGULATION_TEST_STATUS, object.getString("status")); } catch (Throwable e) { e.printStackTrace(); } } }); } private void getFilterDetailTags() { RetrofitManager.getInstance() .getApi().getFilterDetailTags() .subscribe(new Response>() { @Override public void onResponse(@Nullable ArrayList response) { super.onResponse(response); SPUtils.setString(Constants.SP_FILTER_TAGS, GsonUtils.toJson(response)); } }); } private void getAuthDialog() { RetrofitManager.getInstance() .getApi() .authDialog() .subscribe(new Response>() { @Override public void onResponse(@Nullable List response) { super.onResponse(response); SPUtils.setString(Constants.SP_AUTH_DIALOG, GsonUtils.toJson(response)); } }); } @SuppressLint("CheckResult") private void getMark() { // 安装相应包名以后不需请求接口获取返回数据 if (PackageUtils.isInstalled(HaloApp.getInstance().getApplication(), "com.enotary.cloud")) { HaloApp.getInstance().setServerUserMark("new"); return; } RequestBody body; HashMap map = new HashMap<>(); if (mIsNewForThisVersion) { // gid 不存在 (因网络延迟还没获取到时,本地生成一个临时 id 供这个接口用) if (TextUtils.isEmpty(HaloApp.getInstance().getGid()) && TextUtils.isEmpty(HaloApp.getInstance().getTemporaryLocalDeviceId())) { String localTemporaryDeviceId = UUID.randomUUID().toString(); HaloApp.getInstance().setLocalTemporaryDeviceId(localTemporaryDeviceId); SPUtils.setString(Constants.SP_TEMPORARY_DEVICE_ID, localTemporaryDeviceId); } map.put("launch_type", DeviceTokenUtils.getLaunchType(true).name()); } else if (HaloApp.getInstance().isReinstallTheSameVersion()) { map.put("launch_type", LunchType.UPDATE.toString()); } body = ExtensionsKt.toRequestBody(map); RetrofitManager.getInstance() .getApi() .postMark(body) .subscribe(new BiResponse() { @Override public void onSuccess(ResponseBody data) { try { JSONObject object = new JSONObject(data.string()); HaloApp.getInstance().setServerUserMark(object.getString("mark")); } catch (Throwable e) { e.printStackTrace(); } } }); } @SuppressLint("CheckResult") private void showPrivacyPolicy(SimpleCallback callback) { RetrofitManager.getInstance().getApi() .getPrivacyPolicy() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new BiResponse() { @Override public void onSuccess(PrivacyPolicyEntity data) { DialogUtils.showPrivacyPolicyDialog(SplashScreenActivity.this, data, callback); } @Override public void onFailure(@NotNull Exception exception) { DialogUtils.showPrivacyPolicyDialog(SplashScreenActivity.this, PrivacyPolicyEntity.createDefaultData(), callback); } }); } @Override protected int getLayoutId() { if (mIsNewForThisVersion) { return R.layout.activity_splash_intro; } else { return 0; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { if (mIsNewForThisVersion && EasyPermissions.hasPermissions(this, mPermissions)) { launchMainActivity(); } else { return true; } } return super.onKeyDown(keyCode, event); } @Override protected boolean useEventBus() { return false; } // 跳转到主界面 private void launchMainActivity() { SPUtils.setLong(Constants.SP_GH_LAST_UPDATE_TIME, PackageUtils.getHaloLastUpdateTime()); HaloApp.getInstance().postInit(true); TrackerLogger.logAppLaunchSuccessful(); getAd(); prefetchData(); Bundle bundle = getIntent().getExtras(); Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class); if (bundle != null) { intent.putExtras(bundle); } intent.putExtra(MainActivity.SHOW_AD, !mIsNewForThisVersion); overridePendingTransition(0, 0); startActivity(intent); uploadTeaData(); finish(); } @SuppressLint("CheckResult") private void getAd() { AdHelper.getStartUpAd(); } private void uploadTeaData() { if ("tea".equals(BuildConfig.FLAVOR)) { // 在可能获取了相关权限后才初始化SDK/发送激活数据 // TeaHelper.init(getApplication(), HaloApp.getInstance().getChannel()); try { Class clazz = Class.forName("com.gh.gamecenter.TeaHelper"); Method method = clazz.getMethod("init", Context.class, String.class); method.invoke(null, getApplication(), HaloApp.getInstance().getChannel()); } catch (Exception e) { e.printStackTrace(); } } } private void prefetchData() { AppExecutor.getIoExecutor().execute(() -> { Config.getGhzsSettings(); deviceDialogSetting(); getFilterDetailTags(); getAuthDialog(); getMark(); getRegulationTestStatus(); UsageStatsHelper.checkAndPostUsageStats(); GameSubstituteRepositoryHelper.updateGameSubstituteRepository(); // 获取自动刷新的cd,获取版本对应表 String time = mSharedPreferences.getString("refresh_time", null); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); String today = format.format(new Date()); if (!today.equals(time)) { // 获取版本代码、名称 PlatformUtils.getInstance(getApplicationContext()).getPlatform(); TagUtils.getInstance(getApplicationContext()).getTag(); } // 更新本地时间 DeviceTokenUtils.syncServerTime(this); }); } @AfterPermissionGranted(REQUEST_PERMISSION_TAG) private void checkAndRequestPermission() { if (EasyPermissions.hasPermissions(this, mPermissions)) { MtaHelper.onEvent("授权情况", "启动授权", "都授权"); // 检查是否有旧版本光环,有就删掉 AppExecutor.getIoExecutor().execute(this::deleteOutdatedUpdatePackage); if (mStartMainActivityDirectly) { launchMainActivity(); } } else { ActivityCompat.requestPermissions(this, mPermissions, REQUEST_PERMISSION_TAG); } } @Override public void onPermissionsDenied(int requestCode, List perms) { if (mStartMainActivityDirectly) { launchMainActivity(); } } // 检查下载文件夹下是否有旧版本的光环助手的包,有则删除 @SuppressWarnings("ResultOfMethodCallIgnored") private void deleteOutdatedUpdatePackage() { try { File folder = new File(FileUtils.getDownloadDir(this) + File.separator); if (folder.isDirectory()) { for (File file : folder.listFiles()) { if (!file.isDirectory() && file.getName().startsWith("光环助手V")) { String name = file.getName(); int index = name.indexOf("_"); if (index != -1) { String versionString = name.substring(name.indexOf("V") + 1, index); Version currentVersion = new Version(PackageUtils.getGhVersionName()); if (currentVersion.isHigherThan(versionString) || currentVersion.isEqual(versionString)) { file.delete(); } } } } } } catch (Exception e) { e.printStackTrace(); } } private class GuidePagerAdapter extends PagerAdapter { private int[] mPics = {R.drawable.splash_01}; @Override public int getCount() { return mPics.length; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { View view = View.inflate(container.getContext(), R.layout.splash_guide_item, null); ImageView ivImage = view.findViewById(R.id.splsh_guide_iv_image); ivImage.setImageResource(mPics[position]); if (position == mPics.length - 1) { TextView tvSkip = view.findViewById(R.id.splsh_guide_tv_skip); tvSkip.setOnClickListener(v -> launchMainActivity()); } container.addView(view); return view; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView((View) object); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == object; } } }