Search code examples
androidxamarinxamarin.formsxamarin.android

Is there a way to bring the current app that is running code to the foreground Xamarin Forms - Android


I have created a custom document provider for Android using this code as a base.

https://learn.microsoft.com/en-us/samples/xamarin/monodroid-samples/storageprovider/

This allows for a new drive to be mapped onto the documents folder when browsing/saving documents.

If there is an exception due to a password timeout for example, I would like to pop back up the existing app so the users can entered their credentials again to log in.

Is this possible? As an example of what I am looking for, if the QueryRoots failed with a particular exception, could I run something to pop back up the app interface here?

public override ICursor QueryRoots(string[] projection)
{
    Log.Verbose(TAG, "queryRoots");

    var result = new MatrixCursor(ResolveRootProjection(projection));

    try
    {
        if (!IsUserLoggedIn())
        {
            return result;
        }

        MatrixCursor.RowBuilder row = result.NewRow();

        ... other init code here
    }
    catch (Exception ex)
    {
        if (ex.Message == "NoSessionException")
        {
            // LOGIC TO BRING BACK APP TO LOG IN AGAIN HERE...
        }
    }

    return result;
}

Solution

  • I make a sample code about how to lauch the app again for your reference. You could put Launch method in catch statement.

    In Xamarin.Forms, you could use Dependency service to start the app with package name.

    Create a interface:

     public interface IDpendencyService
    {
        Task<bool> Launch(string stringUri);
    }
    

    Implemention of Android:

     public class DependencyImplementation : Activity, IDpendencyService
    {
        public Task<bool> Launch(string stringUri)
        {
    
        Intent intent = Android.App.Application.Context.PackageManager.GetLaunchIntentForPackage(stringUri);
        if (intent != null)
        {
            intent.AddFlags(ActivityFlags.NewTask);
            Forms.Context.StartActivity(intent);
            return Task.FromResult(true);
        }
        else
        {
            return Task.FromResult(true);
        }
    
      }
    }
    

    Register in MainActivity:

     DependencyService.Register<IDpendencyService, DependencyImplementation>();
    

    I use a Button event to invoke. You could try to invoke in catch.

     DependencyService.Get<IDpendencyService>().Launch("com.companyname.xamarindemo");
    

    Screenshot: I have a button on Page21. When i click the button, it would reload the app and pop back up the existing app.

    enter image description here