這一陣新到的這個公司兩個項目準(zhǔn)備開始重構(gòu) 需要用到 AppManager管理Activity 通過Stack 實現(xiàn)先進(jìn)先出宠进,后進(jìn)后出的原則
實現(xiàn)包括:添加Activity到堆棧包斑、獲取當(dāng)前的Activity(堆棧最后一個)长搀、結(jié)束當(dāng)前的Activity(堆棧最后一個)、結(jié)束指定的Activity驻民、結(jié)束指定類名的Activity、結(jié)束所有的Activity等方法。
object AppManager {
private var mActivities: Stack<Activity> = Stack()
/**
* 添加Activity到堆棧
*/
fun attach(activity: Activity) {
mActivities.add(activity)
}
/**
* 將指定Activity移除
*/
fun detach(activity: Activity) {
mActivities.remove(activity)
}
/**
* Get current activity (the last into Stack)
*/
fun currentActivity(): Activity {
return mActivities.lastElement()
}
/**
* Finish current activity (the last into Stack)
*/
fun finishActivity() {
val a = mActivities.lastElement()
a.finish()
}
/**
* Finish the input activity
*/
fun finishActivity(activity: Activity?) {
var size = -1
for (i in mActivities.indices) {
val a = mActivities[i]
if (a == activity) {
size = i
break
}
}
if (size != -1) {
mActivities.removeAt(size)
activity?.finish()
}
}
/**
* finish the activity of afferent class
*/
fun finishActivity(cls: Class<*>) {
for (i in mActivities.indices) {
val a = mActivities[i]
if (a.javaClass.canonicalName == cls.canonicalName) {
mActivities.removeAt(i)
a.finish()
break
}
}
}
/**
* Judge the input Activity is live or die
*/
fun isLive(activity: Activity): Boolean {
return mActivities.contains(activity)
}
/**
* Judge the Activity instance of the input class is live or die
* (the Activity can have more than one object)
*/
fun isLive(cls: Class<*>): Boolean {
mActivities.forEach {
if (it.javaClass.canonicalName == cls.canonicalName)
return true
}
return false
}
/**
* Finish all activity of th mActivities and make mActivities clear
*/
fun finishAllActivity() {
mActivities.forEach {
it?.finish()
}
mActivities.clear()
}
/**
* app exit
*/
@SuppressLint("MissingPermission")
fun appExit(context: Context) {
try {
finishAllActivity()
val activityMgr = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
activityMgr.killBackgroundProcesses(context.packageName)
System.exit(0)
} catch (e: Exception) {
}
}
}
直接copy下來就可以用了 英文不是很好 不過還在學(xué)習(xí)中昨稼, 注釋看看就好