全局获取context

我们在许多地方都需要使用到context,但当程序复杂起来,脱离了activity时,我们通常需要关注是否要将context在函数中传递,那么如何才能简化这个步骤,使得在任何地方都能获取context呢?

Android提供了一个application类,当应用程序启动时,会对这个类进行初始化,我们可以对这个类进行自定义,用来管理全局context

新建一个MyApplication:

1
2
3
4
5
6
7
8
9
10
11
class MyApplication : Application() {

companion object {
lateinit var context : Context
}

override fun onCreate() {
super.onCreate()
context = applicationContext
}
}

这里通过设置了静态变量context获取applicationcontext。系统会提示我们将context设置成全局变量容易引发内存泄漏,但是这里时全局application的context,在整个生命周期内都不会回收,所以不会有上述问题,添加注解忽略即可:

1
2
3
4
5
6
7
8
9
10
11
12
class MyApplication : Application() {

companion object {
@SuppressLint("StaticFieldLeak")
lateinit var context : Context
}

override fun onCreate() {
super.onCreate()
context = applicationContext
}
}

然后在AndroidManifest.xml里面的<application>标签下进行指定:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<application
android:name=".MyApplication"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/net_config"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.WanAndroid"
tools:targetApi="31">
...
</application>

接下来在任何地方只需要调用MyApplication.context即可。

使用Intent传递对象

使用Intent时可以用来启动Activity,Service等,还可以提供一些附加数据。但是这些提供附加数据的类型是有限的,那么如何传递自定义对象呢?

Serializable方式

这个方式是通过将对象进行序列化,转换成一个可存储或可传输的状态,然后传过去后再进行反序列化,比如我们新建一个Person.kt:

1
2
3
4
class Person : Serializable { //继承Serializable接口实现可序列化
var name = ""
var age = 0
}

Activity中进行传递:

1
2
3
4
5
6
val person = Person()
person.name = "Tom"
person.age = 20
val intent = Intent(this, MainActivity2::class.java)
intent.putExtra("person_data", person)
startActivity(intent)

然后获取对象:

1
val person = intent.getSerializableExtra("person_data") as Person

这样就能实现传输了。

Parcelable方式

Parcelable实现方式是将对象进行分解再进行传递。

Kotlin为我们提供了简便的使用Parcelable的方法,不用手动去拆分:

1
2
@Parcelize
class Person(var name: String, var age: Int) : Parcelable

使用这个注解即可,然后Activity中:

1
val person = intent.getParcelableExtra("person_data") as Person

即可获取传递的对象了。