Reputation: 107
I need a way to make my app close and opens again. Or just restart everything inside of it. Since the issue with my app can be fixed by closing app and opening again (When creating user the loading function to firebase the collection inside user document does not load for some reason)
Upvotes: 1
Views: 3617
Reputation: 72
You can use an Extension function if you want to be more concise.
Create a Util folder or module in your project and add a Context.Kt file in it. paste the code below in.
fun Context.restart() {
val packageManager = packageManager
val intent = packageManager.getLaunchIntentForPackage(packageName)!!
val componentName = intent.component!!
val restartIntent = Intent.makeRestartActivityTask(componentName)
startActivity(restartIntent)
Runtime.getRuntime().exit(0)
}
Call the function in your composable like this :
val context = LocalContext.current
Button(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
onClick = { context.restart() }
) {
Text(
text = "Restart",
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
)
}
Upvotes: -1
Reputation: 11
I find this way to be the easiest:
val context = LocalContext.current as Activity
Button(
onClick = { context.recreate() }
) {
Text("Restart Activity")
}
Upvotes: 0
Reputation: 358
So... you could write ways to "restart everything", but I am going to strongly suggest not doing that. When building an app, you will run into edge cases. You will hit some failure states that you can't recover from. That happens. But, solving these cases by just "restarting" doesn't actually address the issue and will probably result in wonky and undesirable UX.
I would instead suggest you post here some steps to reproduce and debugging results.
Without more information, this sounds more like a race condition - you might be trying to find the document before it is actually created and not handling the error path for when the document is not found. However, we would need to do some debugging to verify.
Upvotes: 2
Reputation: 638
Below code can do it:
val context = LocalContext.current
val packageManager: PackageManager = context.packageManager
val intent: Intent = packageManager.getLaunchIntentForPackage(context.packageName)!!
val componentName: ComponentName = intent.component!!
val restartIntent: Intent = Intent.makeRestartActivityTask(componentName)
context.startActivity(restartIntent)
Runtime.getRuntime().exit(0)
Upvotes: 10