Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to restart an Unity app on Android?

I know it is not a good practice to do so but in my particular case it is exactly what I need : I to be able to restart my Unity application (from a native plugin or C#, doesn't matter).

I have tried the code from this link (and even from pure C# here) without success.

like image 480
Tamaya Avatar asked Sep 19 '25 12:09

Tamaya


1 Answers

I managed to get it working with this code :

private static void RestartAndroid() {
    if (Application.isEditor) return;

    using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
        const int kIntent_FLAG_ACTIVITY_CLEAR_TASK = 0x00008000;
        const int kIntent_FLAG_ACTIVITY_NEW_TASK = 0x10000000;

        var currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
        var pm = currentActivity.Call<AndroidJavaObject>("getPackageManager");
        var intent = pm.Call<AndroidJavaObject>("getLaunchIntentForPackage", Application.identifier);

        intent.Call<AndroidJavaObject>("setFlags", kIntent_FLAG_ACTIVITY_NEW_TASK | kIntent_FLAG_ACTIVITY_CLEAR_TASK);
        currentActivity.Call("startActivity", intent);
        currentActivity.Call("finish");
        var process = new AndroidJavaClass("android.os.Process");
        int pid = process.CallStatic<int>("myPid");
        process.CallStatic("killProcess", pid);
    }
}
like image 181
Tamaya Avatar answered Sep 21 '25 01:09

Tamaya