Hello,
Welcome to our Microsoft Q&A platform!
Xamarin Forms detect if app in foreground
Here is achieved by lifecycle to detect app running from background to foreground.
For Forms, you can detect the app from background to foreground by OnResume()
method in the App.xaml.cs
.
If you want to detect the app from background to foreground in different platform.
For Android: Open the MainActivity.cs
, add the OnResume
method.
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
Xamarin.FormsMaps.Init (this, bundle);
LoadApplication (new App ());
}
protected override void OnResume()
{
base.OnResume();
}
}
For iOS
You can access WillEnterForegroundNotification
method in Xamarin.forms project, just override it in AppDelegate.cs
:
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
public override void WillEnterForeground(UIApplication uiApplication)
{
//handle your event here
base.WillEnterForeground(uiApplication);
}
}
If you want to achieve it by dependenceService to get the if app is foreground directly,
For Android.
public bool foregrounded()
{
ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
ActivityManager.GetMyMemoryState(appProcessInfo);
return (appProcessInfo.Importance == Importance.Foreground || appProcessInfo.Importance == Importance.Visible);
}
For iOS
public bool foregrounded()
{
bool isInForeground = UIApplication.SharedApplication.ApplicationState == UIApplicationState.Active;
return isInForeground;
}
Best Regards,
Leon Lu
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.