Merge branch 'feat/refactor_do_on_main_process_implementation' into 'dev'

feat: 重构限制主进程执行的相关代码

See merge request halo/android/assistant-android!1620
This commit is contained in:
陈君陶
2024-04-12 15:29:54 +08:00
21 changed files with 197 additions and 212 deletions

View File

@ -2,17 +2,16 @@ package com.gh.common
import com.gh.common.exposure.ExposureManager
import com.gh.common.filter.RegionSettingHelper
import com.gh.common.util.AdHelper
import com.gh.common.videolog.VideoRecordUtils
import com.gh.download.DownloadDataHelper
import com.gh.gamecenter.common.loghub.LoghubUtils
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.doOnMainProcessOnly
import com.gh.gamecenter.common.utils.tryCatchInRelease
import com.gh.gamecenter.core.runOnUiThread
import com.gh.gamecenter.entity.TimeEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import io.reactivex.schedulers.Schedulers
import kotlin.concurrent.fixedRateTimer
@ -26,7 +25,6 @@ object FixedRateJobHelper {
private const val DOWNLOAD_HEARTBEAT_PERIOD: Long = 60 * 1000L
private const val DOWNLOAD_HEARTBEAT_SHEET_PERIOD: Long = 15 * 1000L
private const val STARTUP_AD: Long = 30 * 60 * 1000L
private var mExecuteCount: Int = 0
@ -34,58 +32,56 @@ object FixedRateJobHelper {
@JvmStatic
fun begin() {
doOnMainProcessOnly {
// 时间检查每15秒检查一次
fixedRateTimer("Global-Fixed-Rate-Timer", initialDelay = 100, period = CHECKER_PERIOD) {
val elapsedTime = mExecuteCount * CHECKER_PERIOD
// 时间校对10分钟一次
if (elapsedTime % TIME_PERIOD == 0L) {
RetrofitManager.getInstance().api.time
.subscribeOn(Schedulers.io())
.subscribe(object : Response<TimeEntity>() {
override fun onResponse(response: TimeEntity?) {
val serverTime = response?.time
serverTime?.let {
timeDeltaBetweenServerAndClient = it * 1000 - System.currentTimeMillis()
}
// 时间检查每15秒检查一次
fixedRateTimer("Global-Fixed-Rate-Timer", initialDelay = 100, period = CHECKER_PERIOD) {
val elapsedTime = mExecuteCount * CHECKER_PERIOD
// 时间校对10分钟一次
if (elapsedTime % TIME_PERIOD == 0L) {
RetrofitManager.getInstance().api.time
.subscribeOn(Schedulers.io())
.subscribe(object : Response<TimeEntity>() {
override fun onResponse(response: TimeEntity?) {
val serverTime = response?.time
serverTime?.let {
timeDeltaBetweenServerAndClient = it * 1000 - System.currentTimeMillis()
}
})
}
// 提交曝光数据
if (elapsedTime % EXPOSURE_PERIOD == 0L) {
ExposureManager.commitSavedExposureEvents(true)
}
// 分片检测下载进度
if (elapsedTime % DOWNLOAD_HEARTBEAT_SHEET_PERIOD == 0L) {
tryCatchInRelease {
val upload = (mExecuteCount * CHECKER_PERIOD) % DOWNLOAD_HEARTBEAT_PERIOD == 0L
DownloadDataHelper.uploadDownloadHeartbeat(upload)
}
}
// 提交普通 loghub 数据
if (elapsedTime % LOGHUB_PERIOD == 0L) {
runOnUiThread {
LoghubUtils.commitSavedLoghubEvents(true)
}
}
// 更新游戏屏蔽信息
if (elapsedTime % REGION_SETTING_PERIOD == 0L) {
if (HaloApp.getInstance().isRunningForeground) {
RegionSettingHelper.getRegionSetting()
}
}
// 提交视频浏览记录数据
if (elapsedTime % VIDEO_RECORD_PERIOD == 0L) {
VideoRecordUtils.commitVideoRecord()
}
mExecuteCount++
}
})
}
// 提交曝光数据
if (elapsedTime % EXPOSURE_PERIOD == 0L) {
ExposureManager.commitSavedExposureEvents(true)
}
// 分片检测下载进度
if (elapsedTime % DOWNLOAD_HEARTBEAT_SHEET_PERIOD == 0L) {
tryCatchInRelease {
val upload = (mExecuteCount * CHECKER_PERIOD) % DOWNLOAD_HEARTBEAT_PERIOD == 0L
DownloadDataHelper.uploadDownloadHeartbeat(upload)
}
}
// 提交普通 loghub 数据
if (elapsedTime % LOGHUB_PERIOD == 0L) {
runOnUiThread {
LoghubUtils.commitSavedLoghubEvents(true)
}
}
// 更新游戏屏蔽信息
if (elapsedTime % REGION_SETTING_PERIOD == 0L) {
if (HaloApp.getInstance().isRunningForeground) {
RegionSettingHelper.getRegionSetting()
}
}
// 提交视频浏览记录数据
if (elapsedTime % VIDEO_RECORD_PERIOD == 0L) {
VideoRecordUtils.commitVideoRecord()
}
mExecuteCount++
}
}
}

View File

@ -6,11 +6,12 @@ import com.alibaba.android.arouter.facade.annotation.Route
import com.gh.common.util.PackageUtils
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.core.provider.IPackageUtilsProvider
import com.gh.gamecenter.core.utils.ProcessUtil
@Route(path = RouteConsts.provider.packageUtils, name = "PackageUtils暴露服务")
class PackageUtilsProviderImpl : IPackageUtilsProvider {
override fun obtainProcessName(context: Context): String? {
return PackageUtils.obtainProcessName(context)
override fun obtainProcessName(): String? {
return ProcessUtil.getCurrentProcessName()
}
override fun getGhVersionName(): String {

View File

@ -125,9 +125,7 @@ public class DataUtils {
HaloApp.getInstance().setGid(gid);
// 更新广告配置
ExtensionsKt.doOnMainProcessOnly(HaloApp.getInstance(), () -> {
AdDelegateHelper.INSTANCE.requestAdConfig(false, "", null);
});
AdDelegateHelper.INSTANCE.requestAdConfig(false, "", null);
getDeviceCertification(gid);
@ -147,11 +145,8 @@ public class DataUtils {
@Override
public void onFailure(String s) {
MtaHelper.onEventWithBasicDeviceInfo("开发辅助", "GID 获取异常", s);
// 更新广告配置
ExtensionsKt.doOnMainProcessOnly(HaloApp.getInstance(), () -> {
AdDelegateHelper.INSTANCE.requestAdConfig(false, "", null);
});
AdDelegateHelper.INSTANCE.requestAdConfig(false, "", null);
}
});
}

View File

@ -888,37 +888,6 @@ public class PackageUtils {
&& !PackageUtils.isSignedByGh(HaloApp.getInstance().getApplication(), apkEntity.getPackageName());
}
/**
* 获取调用者的进程名
*
* @param context 调用者的上下文
* @return 进程名
*/
public static String obtainProcessName(Context context) {
if (PackageFlavorHelper.IS_TEST_FLAVOR) {
try {
final int pid = android.os.Process.myPid();
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> listTaskInfo = am.getRunningAppProcesses();
if (listTaskInfo != null && !listTaskInfo.isEmpty()) {
for (ActivityManager.RunningAppProcessInfo info : listTaskInfo) {
if (info != null && info.pid == pid) {
return info.processName;
}
}
}
} catch (Exception e) {
// 遇到异常了让这次调用正常执行
e.printStackTrace();
return BuildConfig.APPLICATION_ID;
}
} else {
return null;
}
return null;
}
/**
* 应用是否在前台运行
*/

View File

@ -21,7 +21,7 @@ public class ActivitySkipReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ExtensionsKt.doOnMainProcessOnly(context, () -> {
ExtensionsKt.doOnMainProcessOnly(() -> {
if (ACTION_ACTIVITY_SKIP.equals(intent.getAction())) {
Bundle bundle = intent.getExtras();
if (HaloApp.getInstance().isRunningForeground && bundle != null) {
@ -41,6 +41,8 @@ public class ActivitySkipReceiver extends BroadcastReceiver {
context.startActivity(SplashScreenActivity.getSplashScreenIntent(context, bundle));
}
}
return null;
});
}

View File

@ -19,7 +19,7 @@ public class DownloadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ExtensionsKt.doOnMainProcessOnly(context, () -> {
ExtensionsKt.doOnMainProcessOnly(() -> {
try {
if (DownloadNotificationHelper.ACTION_VDOWNLOAD.equals(intent.getAction())) {
DirectUtils.directToVGameDownload(context, "其他", true);
@ -32,6 +32,7 @@ public class DownloadReceiver extends BroadcastReceiver {
ToastUtils.toast(exception.getMessage());
}
}
return null;
});
}

View File

@ -42,7 +42,7 @@ public class InstallAndUninstallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
PackageUtils.dumpInstalledListCache();
ExtensionsKt.doOnMainProcessOnly(context, () -> {
ExtensionsKt.doOnMainProcessOnly(() -> {
Utils.log("InstallAndUninstallReceiver:: onReceive->" + intent.getAction() + "==" + intent.getDataString());
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU
@ -120,6 +120,7 @@ public class InstallAndUninstallReceiver extends BroadcastReceiver {
HaloApp.getInstance().getWebviewAbiList();
}
}
return null;
});
}

View File

@ -40,7 +40,7 @@ public class InstallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ExtensionsKt.doOnMainProcessOnly(context, () -> {
ExtensionsKt.doOnMainProcessOnly(() -> {
String path = intent.getStringExtra(EntranceConsts.KEY_PATH);
DownloadEntity downloadEntity;
String downloadUrl = intent.getStringExtra(EntranceConsts.KEY_URL);
@ -115,6 +115,7 @@ public class InstallReceiver extends BroadcastReceiver {
context.startActivity(SplashScreenActivity.getSplashScreenIntent(context, bundle));
}
}
return null;
});
}

View File

@ -23,7 +23,7 @@ public class NetworkStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// 网络变更这里会被主进程和推送进程分别调用,这里只对主进程响应,
// 奇怪,初次注册监听就会有回调,会导致部分接口短时间内触发两次调用
ExtensionsKt.doOnMainProcessOnly(context, () -> {
ExtensionsKt.doOnMainProcessOnly(() -> {
MetaUtil.updateCachedNetwork();
if (NetworkUtils.isNetworkConnected(context)) {
AdDelegateHelper.INSTANCE.requestAdConfig(true, "", null);
@ -35,6 +35,7 @@ public class NetworkStateReceiver extends BroadcastReceiver {
HaloApp.put(Constants.SHOULD_SHOW_VIDEO_MOBILE_WARNING, true);
}
}
return null;
});
}
}

View File

@ -210,10 +210,6 @@ public class HaloApp extends MultiDexApplication {
super.onCreate();
initArouter();
if (!Injection.appInit(this)) {
return;
}
mInstance = this;
// 每个进程都用自己的进程名作为后缀的文件夹来存 WebView cache
@ -229,57 +225,59 @@ public class HaloApp extends MultiDexApplication {
}
}
for (IApplication application : mApplicationList) {
application.onCreate(mInstance);
}
ExtensionsKt.doOnMainProcessOnly(() -> {
for (IApplication application : mApplicationList) {
application.onCreate(mInstance);
}
// 似乎只是 load SO 不涉及方法调用,所以可以在隐私政策前调用吧?
OAIDHelper.INSTANCE.doSystemLoad();
// 似乎只是 load SO 不涉及方法调用,所以可以在隐私政策前调用吧?
OAIDHelper.INSTANCE.doSystemLoad();
// 70ms
PlayerFactory.setPlayManager(Exo2PlayerManager.class);
CacheFactory.setCacheManager(ExoPlayerCacheManager.class);
PlayerFactory.setPlayManager(Exo2PlayerManager.class);
CacheFactory.setCacheManager(ExoPlayerCacheManager.class);
initFresco();
initFresco();
isNewForThisVersion =
PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.SP_NEW_FIRST_LAUNCH_VERSION + PackageUtils.getGhVersionName(), true);
isNewForThisVersion =
PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.SP_NEW_FIRST_LAUNCH_VERSION + PackageUtils.getGhVersionName(), true);
AppExecutor.getIoExecutor().execute(() -> {
initDataHelper();
ExtensionsKt.doOnMainProcessOnly(this, () -> {
AppExecutor.getIoExecutor().execute(() -> {
initDataHelper();
Tracker.init(this);
DownloadCore.init(this);
deviceRamSize = DeviceUtils.getTotalRamSizeOfDevice(this);
mChannel = mFlavorProvider.getChannelStr(this);
// 初始化推送
initPushEngine();
// 异步初始化 SP
SPUtils.getString("");
});
deviceRamSize = DeviceUtils.getTotalRamSizeOfDevice(this);
mChannel = mFlavorProvider.getChannelStr(this);
RxJavaPlugins.setIoSchedulerHandler(scheduler -> AppExecutor.INSTANCE.getCachedScheduler());
// 初始化阿里云推送
ExtensionsKt.doOnMainProcessOnly(this, this::initPushEngine);
if (isUserAcceptPrivacyPolicy(this)) {
postInit(false);
}
// 异步初始化 SP
SPUtils.getString("");
//设置严格模式
if (BuildConfig.DEBUG) {
StrictMode.VmPolicy policy = new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setVmPolicy(policy);
}
registerActivityLifecycleCallbacks(new GlobalActivityLifecycleObserver());
DarkModeUtils.INSTANCE.initDarkMode();
return null;
});
RxJavaPlugins.setIoSchedulerHandler(scheduler -> AppExecutor.INSTANCE.getCachedScheduler());
if (isUserAcceptPrivacyPolicy(this)) {
postInit(false);
}
//设置严格模式
if (BuildConfig.DEBUG) {
StrictMode.VmPolicy policy = new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setVmPolicy(policy);
}
registerActivityLifecycleCallbacks(new GlobalActivityLifecycleObserver());
DarkModeUtils.INSTANCE.initDarkMode();
}
/**
@ -302,9 +300,7 @@ public class HaloApp extends MultiDexApplication {
DataUtils.init(this, mChannel);
// 初始化广告 SDK
ExtensionsKt.doOnMainProcessOnly(this, () -> {
AdDelegateHelper.INSTANCE.initAdSdk(this);
});
AdDelegateHelper.INSTANCE.initAdSdk(this);
SignatureRepository.INSTANCE.init();
@ -314,29 +310,26 @@ public class HaloApp extends MultiDexApplication {
// https://jira.shanqu.cc/browse/GHZS-3765
// 港澳APP去掉oaid的获取
if (!EnvHelper.isGATApp()) {
ExtensionsKt.doOnMainProcessOnly(() -> {
OAIDHelper.INSTANCE.getOAID(HaloApp.this, (s, isSuccess) -> {
setOAID(s);
MetaUtil.INSTANCE.refreshMeta();
SensorsBridge.INSTANCE.setOAID(s);
OAIDHelper.INSTANCE.getOAID(HaloApp.this, (s, isSuccess) -> {
setOAID(s);
MetaUtil.INSTANCE.refreshMeta();
SensorsBridge.INSTANCE.setOAID(s);
registerPushEngine();
registerPushEngine();
// 上报设备安装事件
if (isNewForThisVersion) {
final LunchType launchType = getLaunchType();
LogUtils.uploadDevice(launchType);
// 上报设备安装事件
if (isNewForThisVersion) {
final LunchType launchType = getLaunchType();
LogUtils.uploadDevice(launchType);
ActivationHelper.sendActivationInfo();
}
return null;
});
ActivationHelper.sendActivationInfo();
}
return null;
});
}
// 获取 settings 配置
ExtensionsKt.doOnMainProcessOnly(this, com.gh.common.constant.Config::getGhzsSettings);
com.gh.common.constant.Config.getGhzsSettings();
String localTemporaryDeviceId = SPUtils.getString(Constants.SP_TEMPORARY_DEVICE_ID);
if (!TextUtils.isEmpty(localTemporaryDeviceId)) {
@ -356,11 +349,9 @@ public class HaloApp extends MultiDexApplication {
RegionSettingHelper.getRegionSetting();
ExtensionsKt.doOnMainProcessOnly(this, () -> {
PackageRepository.initData();
PackageHelper.refreshLocalPackageList();
PackageHelper.initList();
});
PackageRepository.initData();
PackageHelper.refreshLocalPackageList();
PackageHelper.initList();
initReceiver();
initPackageChangesReceiver();
@ -374,7 +365,7 @@ public class HaloApp extends MultiDexApplication {
ProcessLifecycleOwner.get().getLifecycle().addObserver(new ProcessorLifeCycleOwner());
// 初始化畅玩相关数据
ExtensionsKt.doOnMainProcessOnly(this, this::retrieveVGameInfoIfNeeded);
retrieveVGameInfoIfNeeded();
// 开发环境不要强制捕获相关异常,这些异常通常是需要处理的
if (!BuildConfig.DEBUG) {