How to Programmatically Restart a .NET MAUI Android App

Restart a .NET MAUI Android app with C# using Intent.MakeRestartActivityTask and required manifest permissions.

  1. In the AndroidManifest.xml file, add the following code under the <manifest> node.

    1
    2
    
    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" android:maxSdkVersion="32"/>
    <uses-permission android:name="android.permission.USE_EXACT_ALARM" />
    
  2. Add the restart code.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    
    #if ANDROID
    using Android.App;
    using Android.Content;
    using Android.Content.PM;
    using Java.Lang;
    #endif
    
    #if ANDROID   
       var context = Platform.AppContext;
       PackageManager packageManager = context.PackageManager;
       Intent intent = packageManager.GetLaunchIntentForPackage(context.PackageName);
       ComponentName componentName = intent.Component;
       Intent mainIntent = Intent.MakeRestartActivityTask(componentName);
       mainIntent.SetPackage(context.PackageName);
       context.StartActivity(mainIntent);
       Runtime.GetRuntime().Exit(0);
    #endif
    
  3. Test the code in a non-debug environment.

Built with Hugo
Theme Stack designed by Jimmy