In a simple example, how to access the Exit event of our app, without using ViewModel or Hilt, etc.?
For example, to display a simple Toast message, while we exit the app.
The following code, when we press the back button to exit, works properly, and displays the toast:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var ctx = applicationContext
setContent {
checkExit(ctx)
}
}
}
@Composable
fun checkExit(ctx: Context) {
DisposableEffect(""){
onDispose {
Toast.makeText(ctx, "onExit", Toast.LENGTH_LONG).show()
}
}
}
But if we minimize the app and then exit by swiping up the screen in the background, this toast will no longer be displayed
**Working Code, thanks to AgentP**
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var ctx = applicationContext
setContent {
val lifecycle: LifecycleOwner = LocalLifecycleOwner.current
checkExit(ctx, lifecycle)
}
}
}
@Composable
fun checkExit(ctx: Context, lifecycle: LifecycleOwner) {
DisposableEffect(Unit) {
val observer = LifecycleEventObserver { _, event ->
when(event){
Lifecycle.Event.ON_STOP -> {
Toast.makeText(ctx, "onExit", Toast.LENGTH_SHORT).show()
}
}
}
lifecycle.lifecycle.addObserver(observer)
onDispose {
lifecycle.lifecycle.removeObserver(observer)
}
}
}