DemoAppLifecycles.kt 9.85 KB
Newer Older
1 2 3 4 5 6 7 8 9
package com.ydl.component.base


import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Looper
import android.os.Process
YKai committed
10
import androidx.annotation.RequiresApi
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
import android.util.Log
import com.channel.ydl_flutter_base.plugin.YDLCommonPlugin
import com.facebook.stetho.Stetho
import com.meituan.android.walle.WalleChannelReader
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.smtt.sdk.QbSdk
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import com.umeng.socialize.PlatformConfig
import com.umeng.socialize.UMShareAPI
import com.ydl.component.BuildConfig
import com.ydl.component.MainActivity
import com.ydl.media.audio.PlayService
import com.ydl.ydlcommon.actions.crash.Cockroach
import com.ydl.ydlcommon.actions.crash.ExceptionHandler
import com.ydl.ydlcommon.base.config.HttpConfig
import com.ydl.ydlcommon.base.config.YDLConstants
import com.ydl.ydlcommon.base.delegate.IAppLifecycles
import com.ydl.ydlcommon.utils.AppProgressUtils
import com.ydl.ydlcommon.utils.LogUtil
import com.ydl.ydlcommon.utils.YdlBuryPointUtil
import com.ydl.ydlcommon.utils.log.LogHelper
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.config.NimApplication
import io.flutter.view.FlutterMain
import io.reactivex.functions.Action

/**
 * Created by haorui on 2019-09-02.
 * Des:
 */
class DemoAppLifecycles : IAppLifecycles {

    override fun attachBaseContext(base: Context) {

    }

    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    override fun onCreate(application: Application) {
        //模块初始化
        moduleInit(application)
        if (AppProgressUtils.isMainProcess(application)) {
            //第三方SDK初始化
            initThirdServiceSDK(application)
            //Flutter 初始化需要在主线程中执行
            FlutterMain.startInitialization(application)
            YDLCommonPlugin.pluginDelegate = object:YDLCommonPlugin.CommonPluginDelegate  {
                override fun getAppTheme(): HashMap<String, String> {
                    val map = HashMap<String, String>()
                    map["platform_main_theme"] = "#34CD65"
                    return map
                }
63 64 65 66 67 68 69 70 71

                override fun getSubChannelTheme(channelName: String): ArrayList<Any> {
                    val channelTheme = arrayListOf<Any>()
                    val items = mutableMapOf<String, String>()
                    items["index"] = "1"
                    items["type"] = "sort"
                    channelTheme.add(items)
                    return channelTheme
                }
72 73 74 75 76 77 78 79 80
            }
            //        FlutterMain.ensureInitializationComplete(application, null);
            //
            //        FlutterEngine flutterEngine = new FlutterEngine(application);
            //        flutterEngine.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());
            //        YDLCommonPlugin plugin = new YDLCommonPlugin();
            //        flutterEngine.getLocalizationChannel().channel.setMethodCallHandler(plugin);

            val intent = Intent(application, PlayService::class.java)
霍志良 committed
81 82 83 84 85 86
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                application.startForegroundService(intent)
            }else{
                application.startService(intent)

            }
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
            //            application.registerActivityLifecycleCallbacks(new CoursePlayLifecycle());

            Stetho.initializeWithDefaults(application)
        }
    }

    override fun onTerminate(application: Application) {}

    private fun moduleInit(application: Application) {
        NimApplication.getInstance().initIm(application, MainActivity::class.java)
    }


    private fun initThirdServiceSDK(application: Application) {
        object : Thread() {
            override fun run() {
                super.run()
                //设置线程优先级,不与主线程抢资源
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)

                //子线程中初始化X5内核,防止ANR问题
                initX5(application)

                if (DemoGlobalConfig.appEnv == YDLConstants.ENV_PROD) {
                    //                    YDLavManager.Companion.getInstances().init(application, "3387e9b251f3491e9221a9877e8f7830");
                } else {
                    //                    YDLavManager.Companion.getInstances().init(application, "13b1536698f64905a1e7e5bb978ba821");
                }

                //异常拦截
                installCockroach(application)
                //bugly
                val packageName = application.packageName
                var channel = WalleChannelReader.getChannel(application)
                if (channel == null || channel == "null") {
                    channel = "test"
                }
                val strategy = CrashReport.UserStrategy(application)
                strategy.appChannel = channel
                val appkey = if (BuildConfig.DEBUG) "630a3a5cea" else "3939e71afa"
//                CrashReport.initCrashReport(application, appkey, BuildConfig.DEBUG, strategy)

                //umeng
                var umAppkey: String? = null
                if (BuildConfig.FLAVOR.endsWith("ydl")) {
                    umAppkey = "56970affe0f55a9cda001e24"
                    channel = "android_$channel"
                    initUM(umAppkey, channel, application)
                    PlatformConfig.setWeixin(
                        "wx57a9d930270498c7",
                        "17c031f02500ded3457a80e69d8e5e45"
                    )
                    PlatformConfig.setQQZone("1105070461", "6BvkUnk6wXJekcgR")
                } else if (BuildConfig.FLAVOR.endsWith("xlzx")) {
                    umAppkey = "5859e1656e27a42fa400021f"
                    channel = "ATK_7_android_$channel"
                    initUM(umAppkey, channel, application)
                    PlatformConfig.setWeixin(
                        "wx1c6af5a11b5f531f",
                        "1ddb93abbb2d81e604657d38e94a5720"
                    )
                    PlatformConfig.setQQZone("1107931541", "8dCvxUpi525uPGTJ")
                }

                // 选用AUTO页面采集模式
                MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)
                MobclickAgent.setCatchUncaughtExceptions(!BuildConfig.DEBUG)

                //开启友盟集成测试
                UMConfigure.setLogEnabled(BuildConfig.DEBUG)
                HttpConfig.getInstance().initSocketConfig(Action {
                    //数据埋点初始化 (一定要放在主进程中/因为用到了umeng统计,需要放在umeng初始化后)
                    YdlBuryPointUtil.init(application, true)
                })
                //安全检测
                //YDLAppProtector.init();

            }
        }.start()
    }


    private fun initUM(umAppKey: String?, channel: String?, application: Application) {
        /**
         * 初始化common库
         * 参数1:上下文,不能为空
         * 参数2:友盟 app key
         * 参数3:友盟 channel
         * 参数4:设备类型,UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子,默认为手机
         * 参数5:Push推送业务的secret
         */
        UMConfigure.init(application, umAppKey, channel, UMConfigure.DEVICE_TYPE_PHONE, null)
        UMShareAPI.init(application, umAppKey)
    }


    /**
     * 初始化X5内核
     *
     * @param application
     */
    private fun initX5(application: Application) {
        // 在调用TBS初始化、创建WebView之前进行如下配置,以开启优化方案
        //        HashMap map = new HashMap();
        //        map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
        //        QbSdk.initTbsSettings(map);

        //        if (!QbSdk.isTbsCoreInited()) {//// preinit只需要调用一次,如果已经完成了初始化,那么就直接构造view
        //            QbSdk.preInit(application, null);// 设置X5初始化完成的回调接口
        //        }

        val cb = object : QbSdk.PreInitCallback {

            override fun onViewInitFinished(arg0: Boolean) {
                //初始化完成回调
                LogUtil.i("QbSdk onViewInitFinished:$arg0")
            }

            override fun onCoreInitFinished() {
                LogUtil.i("QbSdk onCoreInitFinished")
            }
        }
        QbSdk.initX5Environment(application, cb)

    }

    /**
     * 初始化异常拦截器
     */
    private fun installCockroach(application: Application) {
        val sysExcepHandler = Thread.getDefaultUncaughtExceptionHandler()
        Cockroach.install(application, object : ExceptionHandler() {
            override fun onUncaughtExceptionHappened(thread: Thread, throwable: Throwable) {
                if (BuildConfig.DEBUG) {
                    ToastUtil.toastShort(throwable.message)
                }

                LogHelper.getInstance().writeLogSync(throwable.localizedMessage)
                LogHelper.getInstance().uploadLog(false)
            }

            override fun onBandageExceptionHappened(throwable: Throwable) {
                throwable.printStackTrace()//打印警告级别log,该throwable可能是最开始的bug导致的,无需关心
                LogHelper.getInstance().writeLogSync(throwable.localizedMessage)
            }

            override fun onEnterSafeMode() {}

            override fun onMayBeBlackScreen(e: Throwable?) {
                val thread = Looper.getMainLooper().thread
                Log.e("AndroidRuntime", "--->onUncaughtExceptionHappened:$thread<---", e)
                //黑屏时建议直接杀死app
                sysExcepHandler.uncaughtException(thread, RuntimeException("black screen"))

                LogHelper.getInstance().writeLogSync(e!!.localizedMessage)
            }
        })
    }

}