How to get notified with MonoTouch about my applic

2019-04-29 22:28发布

问题:

Although I think this is a fairly trivial question, I could not find any answers out there.

My question is:

Is there a way to get a notification in a MonoTouch iPhone application when my application is being closed or sent to background (by a user clicking the home button)?

I thought the WillTerminate override was good for this, but in the debugger, it is never called.

回答1:

There are two ways to get notified when an app goes to the background:

a. Override the appropriate method in your AppDelegate:

public override void DidEnterBackground(UIApplication application)
{
    // App entered background, do some light stuff here, 
    // there is not much time before getting suspended
}

b. Add notification observers through the NSNotificationCenter class:

 NSObject observer = NSNotificationCenter.DefaultCenter.AddObserver(
    UIApplication.DidEnterBackgroundNotification, 
    delegate(NSNotification ntf) {

            // Same as above
    });

You can use the NSObject object returned from the AddObserver method to remove the observer when you no longer need it:

NSNotificationCenter.DefaultCenter.RemoveObserver(observer);