Search code examples
androidkotlinandroid-intentandroid-bundlekotlin-companion

How to get packageName in companion object?


I want to make a unique key when i send a intent/bundle to new Activity/Fragment in Android.
So, i decided to use packageName.

companion object {
    val MY_UNIQUE_KEY = "${this@Companion::class.java.packageName}MY_KEY"

    fun newInstance(user: User): UserFragment = UserFragment().apply {
        arguments = bundleOf(
            MY_UNIQUE_KEY  to user
        )
    }
}

But, in this case, i couldn't use this@Companion::class.java.packageName because the android system warns me that it requires API 31(mine supports API 21).

How can i make it? or could you tell me another good way?


Solution

  • You may use the package field for the same. Like so:

    val MY_UNIQUE_KEY = "${this@Companion::class.java.`package`?.name.orEmpty()}MY_KEY"