简体   繁体   中英

How to detect when app moves to background or foreground in UIViewController class xamarin.ios

I need to enable and disable some timers when app moves to background or foreground that lives in a UIViewController. But it seems I can only access the DidEnterBackground and WillEnterForeground only in AppDelegate class. Is there any way to detect these two events from UIViewController class?

You can't access those event in uiviewcontroller level, you can only get them in App level.

In the AppDelegate, you can send notification when use DidEnterBackground or WillEnterForeground :

public class AppDelegate : UIResponder, IUIApplicationDelegate {

    [Export("window")]
    public UIWindow Window { get; set; }

    [Export ("application:didFinishLaunchingWithOptions:")]
    public bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
    {
        // Override point for customization after application launch.
        // If not required for your application you can safely delete this method
        return true;
    }

    [Export("applicationDidEnterBackground:")]
    public virtual void DidEnterBackground(UIKit.UIApplication application) {

        NSNotificationCenter.DefaultCenter.PostNotificationName("DidEnterBackground",this);
    }

    [Export("applicationWillEnterForeground:")]
    public virtual void WillEnterForeground(UIKit.UIApplication application) {

        NSNotificationCenter.DefaultCenter.PostNotificationName("WillEnterForeground", this);
    }      
}

Then in the UIViewController which you want to know, AddObserver:

public partial class ViewController : UIViewController
{
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        // Perform any additional setup after loading the view, typically from a nib.

        NSString backgroundStr = new NSString("DidEnterBackground");
        NSString foregroundStr = new NSString("WillEnterForeground");

        NSNotificationCenter.DefaultCenter.AddObserver(backgroundStr, enterBackgroundMethod);
        NSNotificationCenter.DefaultCenter.AddObserver(foregroundStr, enterForegroundMethod);

    }

    public void enterBackgroundMethod(NSNotification notification)
    {
        Console.WriteLine("enterBackgroundMethod");
    }

    public void enterForegroundMethod(NSNotification notification)
    {
        Console.WriteLine("enterForegroundMethod");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM