找到找到应用程序启动的方法(至少是第一个活动启动),然后根据需要在onCreate()
. 我面临和你一样的情况,应用程序在启动和离开时必须做一些事情。我创建了一个界面来监听应用程序进入前台和后台模式(没有正在运行的活动):
interface IApplicationLifeCycle {
fun onEnterForeground()
fun onEnterBackground()
fun onFirstCreated()
fun onLastDestroyed()
}
然后我创建一个类来检测应用程序正在进入后台和前台
class AppLifeCycleTracker(private val iApplicationLifeCycle: IApplicationLifeCycle? = null) : Application.ActivityLifecycleCallbacks {
private var aliveActivityCount = 0 // created on destroyed
private var activeActivityCount = 0 // started on stopped
private var liveActivityCount = 0 // resumed on paused
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
aliveActivityCount++
if (aliveActivityCount == 1) {
iApplicationLifeCycle?.onFirstCreated()
}
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
override fun onActivityStarted(activity: Activity) {
activeActivityCount++
}
override fun onActivityResumed(activity: Activity) {
liveActivityCount++
if (liveActivityCount == 1 && activeActivityCount == 1) {
iApplicationLifeCycle?.onEnterForeground()
}
}
override fun onActivityPaused(activity: Activity) {
liveActivityCount--
}
override fun onActivityStopped(activity: Activity) {
activeActivityCount--
if (liveActivityCount == 0 && activeActivityCount == 0) {
iApplicationLifeCycle?.onEnterBackground()
}
}
override fun onActivityDestroyed(activity: Activity) {
aliveActivityCount--
if (aliveActivityCount == 0) {
iApplicationLifeCycle?.onLastDestroyed()
}
}
}
在我的申请中
class MyApplication: IApplicationLifeCycle{
onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(AppLifeCycleTracker(this))
}
override fun onEnterForeground() {
Log.i("AppVisibility", "onEnterForeground")
// do action here
}
...
...
...
}
在被覆盖的方法上,onEnterForeground
只做你想做的动作,在这种情况下,你想做一些初始化