Skip to content

Instantly share code, notes, and snippets.

@easterapps
Last active March 23, 2024 18:44
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save easterapps/7127ce0749cfce2edf083e55b6eecec5 to your computer and use it in GitHub Desktop.
Save easterapps/7127ce0749cfce2edf083e55b6eecec5 to your computer and use it in GitHub Desktop.
restart android application programmatically
fun triggerRestart(context: Activity) {
val intent = Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
if (context is Activity) {
(context as Activity).finish()
}
Runtime.getRuntime().exit(0)
}
@karloberas
Copy link

Works like a charm for Andriod 10

@VitKap
Copy link

VitKap commented Oct 27, 2020

Yes, great work. This would also reload the Application class - so it is an app restarter.

Also I use it as an extension function fun Activity.triggerRestart

@danielehrhardt
Copy link

Is it possible if the User exists the App that it will automatically restart?

@easterapps
Copy link
Author

easterapps commented Dec 30, 2020

Is it possible if the User exists the App that it will automatically restart?

@danielehrhardt I think it should work, but haven't tested it yet

@albertomna
Copy link

Sorry i didn't understand how put the code in a project. I must put in a different class? I must put a Receive, Service? Thank you so much!

@nikolamin
Copy link

Awesome, this satisfies The app called finish() on an activity very recently.

Also,
Runtime.getRuntime().exit(0) can be replaced with kotlin.system.exitProcess(0)

@Kudlayra
Copy link

Finally! It helped me to delete database and recreate with default data. Thanks.

@russellhoff
Copy link

I can't get it work, sorry

package com.mycompany.myapp.util

import android.app.Activity
import android.content.Intent
import com.mycompany.myapp.ui.MainActivity

fun triggerRestart(context: Activity) {
    val intent = Intent(context, MainActivity::class.java).apply {
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    context.startActivity(intent)
    context.finish()
    kotlin.system.exitProcess(0)
}

@VitKap
Copy link

VitKap commented Oct 13, 2022

@russellhoff how about to replace kotlin.system.exitProcess(0) with Runtime.getRuntime().exit(0)?

@russellhoff
Copy link

already tried but with no success

@VitKap
Copy link

VitKap commented Oct 25, 2022

already tried but with no success
Try to explain what is not working. It works on Andoid SDK 31, called from the main thread.

@Omar-D
Copy link

Omar-D commented Jul 31, 2023

@easterapps thank you very much it works like a charm on all devices ❤️

@tkkcc
Copy link

tkkcc commented Sep 2, 2023

awesome, help me solve memory leak of DexClassLoader

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment