package com.fuying.sn.base; import android.annotation.SuppressLint; import android.app.Application; import android.content.Intent; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.util.Log; import com.alibaba.sdk.android.push.CloudPushService; import com.alibaba.sdk.android.push.CommonCallback; import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory; import com.arialyy.aria.core.Aria; import com.fuying.sn.BuildConfig; import com.fuying.sn.data.repository.DeviceRepository; import com.fuying.sn.desktop.RunningAppManager; import com.fuying.sn.desktop.TimeControlManager; import com.fuying.sn.disklrucache.CacheHelper; import com.fuying.sn.manager.AmapManager; import com.fuying.sn.manager.ControlManager; import com.fuying.sn.manager.DeviceManager; import com.fuying.sn.manager.time.TimeManager; import com.fuying.sn.push.PushManager; import com.fuying.sn.rlog.LogDBManager; import com.fuying.sn.service.DownloadService; import com.fuying.sn.service.ManagerService; import com.fuying.sn.service.SocketService; import com.fuying.sn.service.main.MainService; import com.fuying.sn.sync.AppInventorySync; import com.fuying.sn.sync.AppPolicySync; import com.fuying.sn.sync.AppUpdateCoordinator; import com.fuying.sn.sync.AppUsageReporter; import com.fuying.sn.sync.BrowserPolicySync; import com.fuying.sn.sync.DeviceProfileSync; import com.fuying.sn.sync.DeviceSettingsSync; import com.fuying.sn.sync.PushTagSync; import com.fuying.sn.sync.RemoteDiagnostics; import com.fuying.sn.sync.TimePolicySync; import com.fuying.sn.utils.AppUsedTimeUtils; import com.fuying.sn.utils.JgyUtils; import com.fuying.sn.utils.SystemUtils; import com.fuying.sn.utils.Utils; import com.hjq.toast.Toaster; import com.tencent.bugly.crashreport.CrashReport; import com.tencent.mmkv.MMKV; public class BaseApplication extends Application { private static final String TAG = "BaseApplication"; /** * 兜底循环内允许的连续主线程异常次数,超过后交回默认处理器重启进程 */ private static final int MAX_CONTINUOUS_CRASH = 5; /** * 两次主线程异常超过该间隔(毫秒)就重新计数,避免偶发异常被累计成连续崩溃 */ private static final long CRASH_RESET_INTERVAL = 30_000L; /** * ViewModel中因为经常旋转导致弱引用为空 */ @SuppressLint("StaticFieldLeak") private static BaseApplication sInstance; public static BaseApplication getInstance() { return sInstance; } @Override public void onCreate() { super.onCreate(); sInstance = this; //非主进程不初始化 if (SystemUtils.isMainProcessName(this, android.os.Process.myPid())) { if (BuildConfig.DEBUG) { //静音 // AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // int ringMax = audioManager.getStreamMinVolumeInt(AudioManager.STREAM_RING); // audioManager.setStreamVolume(AudioManager.STREAM_RING, ringMax, 0); // int musicMax = audioManager.getStreamMinVolumeInt(AudioManager.STREAM_MUSIC); // int voiceMax = audioManager.getStreamMinVolumeInt(AudioManager.STREAM_VOICE_CALL); // audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, voiceMax, 0); // audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicMax, 0); //音乐音量 Log.e(TAG, "debugTest: " + getExternalCacheDir()); Log.e(TAG, "debugTest: " + getExternalFilesDir("cache")); Log.e(TAG, "debugTest: " + getCacheDir()); Log.e(TAG, "debugTest: " + Environment.getExternalStorageDirectory()); } utilsInint(); } } private void utilsInint() { String rootDir = MMKV.initialize(this); Log.i(TAG, "mmkv root: " + rootDir); PushManager.init(this); aliyunPushInit(); Toaster.init(this); JgyUtils.init(this); CrashReport.initCrashReport(getApplicationContext(), "e5f026c8d5", false); CrashReport.setDeviceId(this, Utils.getSerial()); if (!BuildConfig.DEBUG) { // Bugly 先接管默认异常处理器,兜底处理器才能把子线程异常继续传递给它完成上报 catchException(); } LogDBManager.init(this); Aria.init(this); Aria.download(this).resumeAllTask(); CacheHelper syncCache = new CacheHelper(this); DeviceRepository.init(this, syncCache); DeviceProfileSync.init(this); PushTagSync.init(); AppInventorySync.init(this); BrowserPolicySync.init(this); AppPolicySync.init(this, syncCache); DeviceSettingsSync.init(this, syncCache); RemoteDiagnostics.init(this); TimePolicySync.init(this, syncCache); AppUpdateCoordinator.init(this, syncCache); AppUsageReporter.init(this); if (BuildConfig.VERSION_CODE < 88) { RunningAppManager.init(this); } else { TimeManager.init(this); } TimeControlManager.init(this); ControlManager.init(this); // ControlPanelManager.init(this); DeviceManager.init(this); AmapManager.init(this); AppUsedTimeUtils.init(this); JgyUtils.hookWebView(); startService(); } @Override public void onTerminate() { super.onTerminate(); TimeManager.getInstance().onDestroy(); } private void startService() { startService(new Intent(this, MainService.class)); startService(new Intent(this, SocketService.class)); startService(new Intent(this, DownloadService.class)); startService(new Intent(this, ManagerService.class)); } /** * 线上崩溃兜底:主线程单次异常只记录并继续分发消息,避免常驻进程被一次异常打断; * 子线程异常继续交给原有处理器(Bugly),保证崩溃能正常上报。 */ private void catchException() { final Thread.UncaughtExceptionHandler originHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { logCrash("子线程", t, e); if (originHandler != null) { // 不吞掉异常:默认处理器里是 Bugly 的上报与系统退出逻辑 originHandler.uncaughtException(t, e); } else { Log.e(TAG, "catchException: 默认异常处理器为空,子线程崩溃无法上报"); } } }); // 主线程消息分发的异常会冒泡出 Looper.loop() 直接结束进程,用嵌套循环拦下来单独记录 new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { int crashCount = 0; long lastCrashTime = 0L; while (true) { try { Looper.loop(); // 接管主线程消息分发,消息里抛出的异常会落到下面的 catch } catch (Throwable e) { long now = System.currentTimeMillis(); if (now - lastCrashTime > CRASH_RESET_INTERVAL) { crashCount = 0; } lastCrashTime = now; crashCount++; logCrash("主线程", Thread.currentThread(), e); if (e instanceof Error || crashCount >= MAX_CONTINUOUS_CRASH) { // Error 不可恢复、或短时间内反复崩溃说明进程状态已不可信, // 交回默认处理器让系统按 START_STICKY 重新拉起,不再继续兜底 Log.e(TAG, "catchException: 主线程连续异常次数=" + crashCount); if (originHandler != null) { originHandler.uncaughtException(Thread.currentThread(), e); return; } throw new RuntimeException("默认异常处理器为空", e); } reportCatchedException(e); } } } }); } private void logCrash(String source, Thread thread, Throwable e) { // 直接取 getStackTrace()[0] 在堆栈为空时会在异常处理里二次崩溃,这里取完整堆栈 Log.e(TAG, "logCrash: " + source + " thread=" + thread.getName() + " 在:" + Log.getStackTraceString(e)); } private void reportCatchedException(Throwable e) { try { // 被兜底拦下的异常不会经过 Bugly 的 UncaughtExceptionHandler,必须主动上报 CrashReport.postCatchedException(e); } catch (Throwable reportError) { Log.e(TAG, "reportCatchedException: 崩溃上报失败 " + Log.getStackTraceString(reportError)); } } private void aliyunPushInit() { // PushInitConfig pushInitConfig = new PushInitConfig.Builder() // .application(this) // // 开启channel进程 // .disableChannelProcess(true) // // 开启channel进程心跳 // .disableChannelProcessHeartbeat(true) // .build(); // // PushServiceFactory.init(pushInitConfig); PushServiceFactory.init(this); CloudPushService pushService = PushServiceFactory.getCloudPushService(); // pushService.setPushIntentService(AliMessageIntentService.class); pushService.setLogLevel(CloudPushService.LOG_DEBUG); pushService.register(this, new CommonCallback() { @Override public void onSuccess(String response) { Log.e("AliyunPush", "init cloudchannel success"); Log.e("AliyunPush", "init cloudchannel success " + pushService.getDeviceId()); String sn = Utils.getSerial(); Log.e(TAG, "AliyunPush: sn=" + sn); if (TextUtils.isEmpty(sn)) { return; } pushService.bindAccount(sn, new CommonCallback() { @Override public void onSuccess(String s) { Log.e("AliyunPush", "bind account " + sn + " success\n"); } @Override public void onFailed(String errorCode, String errorMsg) { Log.e("AliyunPush", "bind account " + sn + " failed." + "errorCode: " + errorCode + ", errorMsg:" + errorMsg); } }); pushService.addAlias(sn, new CommonCallback() { @Override public void onSuccess(String s) { Log.e("AliyunPush", "add alias " + sn + " success\n"); } @Override public void onFailed(String errorCode, String errorMsg) { Log.e("AliyunPush", "add alias " + sn + " failed." + "errorCode: " + errorCode + ", errorMsg:" + errorMsg + "\n"); } }); pushService.bindTag(CloudPushService.DEVICE_TARGET, new String[]{BuildConfig.platform}, null, new CommonCallback() { @Override public void onSuccess(String s) { Log.e("AliyunPush", "add tag " + sn + " success\n"); } @Override public void onFailed(String errorCode, String errorMsg) { Log.e("AliyunPush", "add tag " + sn + " failed." + "errorCode: " + errorCode + ", errorMsg:" + errorMsg + "\n"); } }); } @Override public void onFailed(String errorCode, String errorMessage) { Log.e("AliyunPush", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage); } }); } }