Search code examples
c#androidandroid-intentmaui

OnActivityResult after application restart


I am developing a .NET Maui application. It is sideloaded and doesn't use the Google Play Store.

I want to update the app by downloading the new Apk and starting an ACTION_VIEW activity on the Apk. This works great for updating the app.

var installIntent = new Intent(Intent.ActionView);
installIntent.AddFlags(ActivityFlags.ClearTop);
installIntent.AddFlags(ActivityFlags.GrantReadUriPermission);

installIntent.SetDataAndType(apkUri?.NormalizeScheme(), GetMimeType());
MainActivity.Current.StartActivityForResult(installIntent, Config.UPDATE_ACTIVITY_REQUEST_CODE );

However, I need to take some actions after the app was updated or the update canceled. For this, I have the following method in MainActivity:

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent? data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.UPDATE_ACTIVITY_REQUEST_CODE)
        {
            if (resultCode == Result.Ok)
            {
                // Do things after sucessfull update
            }
            else if (resultCode == Result.Canceled)
            {
                // Do things after canceled update
            }
        }
    }

If the user rejects the update, OnActivityResult is called and everything works as expected. If the user accepts the update, the application is restarted automatically and the OnActivityResult is never called.

How do I make it so that OnActivityResult is called, either before or after the application-restart? Or am I on the wrong path here by using ActivityResult?


Solution

  • That's an expected behavior: the app is killed while updating, so you can't use onActivityResult for it. A possible solution would be to register a broadcast receiver in AndroidManifest with ACTION_MY_PACKAGE_REPLACED action.