毕设中需要进入A关闭B页面,于是想到的使用Activity管理器,之前使用的是用List<T>存放每一个Activity,现在在网上看到Stack<T>是更符合Activity管理逻辑 “后进先出”,因为不是很了解Stack<T>,所以感觉两者使用使用上大致相同
class ActivitysManager {
private val activityStack : Stack<Activity> = Stack()
//创建静态方法获取ActivitysManager
companion object {
val instance : ActivitysManager by lazy { ActivitysManager() }
}
//指定类名关闭Activity
fun finishActivity(className : String){
for (activity in activityStack){
if((activity::class.java.simpleName) == className){
activity.finish()
return
}
}
}
fun addActivity(activity : Activity){
activityStack.add(activity)
}
fun removeActivity(activity: Activity){
activityStack.remove(activity)
}
fun getTopActivity():Activity{
return activityStack.lastElement()
}
fun clearActivity(){
activityStack.forEach { it.finish() }
activityStack.clear()
}
fun exitAPP(context: Context){
clearActivity()
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
activityManager.killBackgroundProcesses(context.packageName)
exitProcess(0)
}
}
网友评论