文章目录
Activity的最佳实践 知晓当前是在哪一个Activiy 随时随地退出程序 启动Activity的最佳写法
Activity的最佳实践
知晓当前是在哪一个Activiy
创建一个BaseActivity类,继承AppCompatActivity类.重写onCreate方法
open class BaseActivity : AppCompatActivity ( ) {
override fun onCreate ( savedInstanceState: Bundle? ) {
super . onCreate ( savedInstanceState)
Log. d ( "BaseActivity" , javaClass. simpleName)
}
}
修改FirstActivity等的代码,让他们不再继承AppCompatActivity而是继承自BaseAvtivity 记住要想让自己能够被别人所继承,要在class前面加上open关键字 运行项目代码依次点击按钮进入相应的Activity,观察日志输出,现在我们每当进入一个Activity的界面,该Activity的类名就会被打印出来了,这样我们就能够知道当前的界面是哪一个Activity了
随时随地退出程序
package com. zb. activitytest. util
import android. app. Activity
object ActivityCollector {
private val activities = ArrayList< Activity> ( )
fun addActivity ( activity: Activity) {
activities. add ( activity)
}
fun removeActivity ( activity: Activity) {
activities. remove ( activity)
}
fun finishAll ( ) {
for ( activity in activities) {
if ( ! activity. isFinishing) {
activity. finish ( )
}
}
activities. clear ( )
}
}
open class BaseActivity : AppCompatActivity ( ) {
override fun onCreate ( savedInstanceState: Bundle? ) {
super . onCreate ( savedInstanceState)
Log. d ( "BaseActivity" , javaClass. simpleName)
ActivityCollector. addActivity ( this )
}
override fun onDestroy ( ) {
super . onDestroy ( )
ActivityCollector. removeActivity ( this )
}
}
以后不论在程序的哪个位置,想要直接退出程序的话,只需要调用ActivityCollector.finishAll()方法即可 当然还可以在销毁Activity的代码后面加上杀掉当前进程的代码,以保证程序可以完全的退出
android. os. Process. killProcess ( android. os. Process. myPid ( ) )
启动Activity的最佳写法
在自己的Activity中定义一个actionStart()方法,在里面包装自己需要的参数 例如SecondActivity中写一个actionStart()方法
companion object {
fun actionStart ( context: Context, data1: String, data2: String) {
val intent = Intent ( context, SecondActivity:: class . java)
intent. putExtra ( "data1" , data1)
intent. putExtra ( "data2" , data2)
context. startActivity ( intent)
}
}
FirstActivity在跳转到SecondActivity的时候就知道自己要给对方传递什么数据了,而且这种方式启动activity只需要一行代码即可
SecondActivity. actionStart ( this , "1111" , "2222" )