registerActivityLifecycleCallbacks是Application的一个接口,注册之后应用里的所有Activity的生命周期都会被“使用”起来
1.在AndroidManifest.xml中修改默认的Application为我们的MyApplication类,代码如下:
......
<application
android:name="com.xxx.xxx.MyApplication"//添加这一句
......
1.1 MyApplication.kt
......
override fun onCreate() {
super.onCreate()
init()
}
private fun init(){
rigesterActivityCallbacks()
}
private fun rigesterActivityCallbacks() {
registerActivityLifecycleCallbacks(ActivityLifecycleCallbacksAdapter(
onActivityCreated = {
activity, _ ->
//开启一个个新Activity会被使用起来
ActivityManager.activities.add(activity)
},
))
}
......
1.1.1 ActivityLifecycleCallbacksAdapter.kt
class ActivityLifecycleCallbacksAdapter(
private var onActivityCreated: ((activity: Activity, savedInstanceState: Bundle?) -> Unit)? = null,
) : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
onActivityCreated?.invoke(activity, savedInstanceState)
}
override fun onActivityStarted(activity: Activity) {
return
}
override fun onActivityResumed(p0: Activity) {
return
}
override fun onActivityPaused(p0: Activity) {
return
}
override fun onActivityStopped(p0: Activity) {
return
}
override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
return
}
override fun onActivityDestroyed(p0: Activity) {
return
}
}
1.1.2 ActivityManager.kt,带注释说明的代码如下:
object ActivityManager {
val activities = mutableListOf<Activity>()
//因为clazz改不class,class是关键的,class表示:目标的Activity
fun start(clazz: Class<out Activity>) {
//currentActivity表示:当前刚开启的Activity
val currentActivity = activities[activities.lastIndex]
val intent = Intent(currentActivity, clazz)
currentActivity.startActivity(intent)
}
}
1.1.2.1一个非Activity转跳到另一个Activity,代码如下,这代码很特殊,start函数调用到1.1.2代码中,容易理解
var cls: Class<out Activity>? = null
cls = MyListActivity::class.java
cls?.let {
ActivityManager.start(
it//it表示目标的Activity
)
}