Junior
How to determine if an activity is opening for the first time?
sobes.tech AI
Answer from AI
You can check for saved state in onCreate: if null, the activity is created for the first time (without restoration after destruction). You can also use a flag in SharedPreferences or a static variable, but these are less reliable approaches for determining the first launch of the activity within the current process.
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my)
if (savedInstanceState == null) {
// Activity is created for the first time
} else {
// Activity is restored from saved state
}
}
}
To determine the first launch of the application or a specific screen during the entire installation period, use SharedPreferences:
class MyActivity : AppCompatActivity() {
private val PREFS_NAME = "MyPrefs"
private val KEY_FIRST_LAUNCH = "firstLaunch"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my)
val prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
val isFirstLaunch = prefs.getBoolean(KEY_FIRST_LAUNCH, true)
if (isFirstLaunch) {
// This is the first launch of the app or this screen
// Perform first launch actions
// Save flag that first launch has been done
val editor = prefs.edit()
editor.putBoolean(KEY_FIRST_LAUNCH, false)
editor.apply()
} else {
// Not the first launch
}
}
}