Files
assistant-android/app/src/main/java/com/gh/gamecenter/SplashScreenActivity.java

485 lines
18 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 android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
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.PrivacyDialogFragment;
import com.gh.common.tracker.Tracker;
import com.gh.common.tracker.TrackerLogger;
import com.gh.common.util.AdHelper;
import com.gh.common.util.DeviceTokenUtils;
import com.gh.common.util.DeviceUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.GameSubstituteRepositoryHelper;
import com.gh.common.util.GsonUtils;
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.manager.FilterManager;
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.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
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.getVersionName(), true);
HaloApp.getInstance().isNewForThisVersion = mIsNewForThisVersion;
super.onCreate(savedInstanceState);
DisplayUtils.transparentStatusBar(this);
TrackerLogger.logAppLaunch(Tracker.INSTANCE.getLaunchId(), Tracker.INSTANCE.getSessionId());
// 处理助手已经在后台运行导致的再次启动助手
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)) {
mStartMainActivityDirectly = true;
SPUtils.setLong(Constants.SP_INITIAL_USAGE_TIME, System.currentTimeMillis());
HaloApp.getInstance().isBrandNewInstall = true;
showPrivacyDialog(guideLayout);
} else {
cancelPreviousUpdateTask();
guideLayout.setVisibility(View.VISIBLE);
// requestPermission();
}
} else {
launchMainActivity();
}
SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, "");
SPUtils.setString(Constants.SP_XAPK_URL, "");
}
private void showPrivacyDialog(ViewPager guideLayout) {
PrivacyDialogFragment.show(this, (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<DownloadEntity> all = DownloadManager.getInstance(this).getAllDownloadEntity();
for (DownloadEntity downloadEntity : all) {
if (downloadEntity.getPackageName().equals(getPackageName())) {
DownloadManager.getInstance(this).cancel(downloadEntity.getUrl(), true, true);
break;
}
}
}
private void requestPermission() {
if (!EasyPermissions.hasPermissions(this, mPermissions)) {
checkAndRequestPermission();
}
}
@SuppressLint("CheckResult")
private void deviceDialogSetting() {
RetrofitManager.getInstance(HaloApp.getInstance().getApplication())
.getSensitiveApi().deviceDialogs()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BiResponse<List<DeviceDialogEntity>>() {
@Override
public void onSuccess(List<DeviceDialogEntity> entities) {
if (entities.size() > 0) {
SPUtils.setString(Constants.SP_DEVICE_REMIND, GsonUtils.toJson(entities));
}
}
});
}
@SuppressLint("CheckResult")
private void getRegulationTestStatus() {
RetrofitManager.getInstance(HaloApp.getInstance().getApplication())
.getApi().getRegulationTestStatus()
.subscribe(new BiResponse<ResponseBody>() {
@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(HaloApp.getInstance().getApplication())
.getSensitiveApi().getFilterDetailTags()
.subscribe(new Response<ArrayList<String>>() {
@Override
public void onResponse(@Nullable ArrayList<String> response) {
super.onResponse(response);
SPUtils.setString(Constants.SP_FILTER_TAGS, GsonUtils.toJson(response));
}
});
}
private void getAuthDialog() {
RetrofitManager.getInstance(HaloApp.getInstance().getApplication())
.getSensitiveApi()
.authDialog()
.subscribe(new Response<List<AuthDialogEntity>>() {
@Override
public void onResponse(@Nullable List<AuthDialogEntity> response) {
super.onResponse(response);
SPUtils.setString(Constants.SP_AUTH_DIALOG, GsonUtils.toJson(response));
}
});
}
@SuppressLint("CheckResult")
private void getMark() {
RetrofitManager.getInstance(HaloApp.getInstance().getApplication())
.getApi()
.getMark()
.subscribe(new BiResponse<ResponseBody>() {
@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<Boolean> callback) {
RetrofitManager.getInstance(this).getApi()
.getPrivacyPolicy()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BiResponse<PrivacyPolicyEntity>() {
@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;
}
@Override
protected boolean useButterKnife() {
return false;
}
// 跳转到主界面
private void launchMainActivity() {
HaloApp.getInstance().postInit(true);
TrackerLogger.logAppLaunchSuccessful(Tracker.INSTANCE.getLaunchId(), Tracker.INSTANCE.getSessionId());
getAd();
prefetchData();
uploadTeaAndGdtData();
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);
// TODO 是否可以放在子线程上报?
uploadTeaAndGdtData();
finish();
}
@SuppressLint("CheckResult")
private void getAd() {
AdHelper.getStartUpAd();
}
private void uploadTeaAndGdtData() {
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();
}
}
// GdtHelper.INSTANCE.logAction(ActionType.START_APP, GdtHelper.NETWORK_TYPE, DeviceUtils.getNetwork(this));
if ("gdt".equals(BuildConfig.FLAVOR)) {
try {
Class<?> clazz = Class.forName("com.gh.gamecenter.GdtHelper");
Field field = clazz.getDeclaredField("NETWORK_TYPE");
String type = (String) field.get(null);
Method method = clazz.getMethod("logAction", String.class, String[].class);
Class<?> actionTypeClazz = Class.forName("com.qq.gdt.action.ActionType");
Field typeField = actionTypeClazz.getDeclaredField("START_APP");
String actionType = (String) typeField.get(null);
method.invoke(null, actionType, new String[]{type, DeviceUtils.getNetwork(this)});
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void prefetchData() {
AppExecutor.getIoExecutor().execute(() -> {
Config.getGhzsSettings();
deviceDialogSetting();
getFilterDetailTags();
getAuthDialog();
getMark();
getRegulationTestStatus();
UsageStatsHelper.checkAndPostUsageStats();
GameSubstituteRepositoryHelper.updateGameSubstituteRepository();
// 第一次启动把package.txt文件内容加载进数据库
FilterManager filterManager = new FilterManager(getApplicationContext());
if (!mSharedPreferences.getBoolean("isLoadFilterV2d4", false)) {
filterManager.loadFilter();
}
// 获取过滤包
filterManager.getFilterFromServer(0);
// 更新过滤表获取自动刷新的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<String> 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.getVersionName());
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;
}
}
}