2010-10-04 16 views
26

如何檢測到應用程序剛剛從「後臺模式」返回?我的意思是,當用戶按下「主頁按鈕」時,我不希望我的應用程序獲取數據(每60秒)。但是,我想在應用程序處於前景模式時進行一些「特殊」更新。iphone 4 sdk:檢測從後臺模式返回

如何檢測這兩個事件:

  1. 應用將背景模式
  2. 應用提前去前臺模式

感謝。

弗朗索瓦

回答

48

以下是如何對此類事件監聽:

// Register for notification when the app shuts down 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationWillTerminateNotification object:nil]; 

// On iOS 4.0+ only, listen for background notification 
if(&UIApplicationDidEnterBackgroundNotification != nil) 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationDidEnterBackgroundNotification object:nil]; 
} 

// On iOS 4.0+ only, listen for foreground notification 
if(&UIApplicationWillEnterForegroundNotification != nil) 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationWillEnterForegroundNotification object:nil]; 
} 

注:if(&SomeSymbol)檢查,確保您的代碼將在iOS 4.0以上版本,並在iOS 3.x的工作 - 如果你建立針對iOS 4.x或5.x SDK並將部署目標設置爲iOS 3.x,則您的應用仍可以在3.x設備上運行,但相關符號的地址將爲零,因此它不會嘗試詢問用於3.x設備上不存在的通知(這會導致應用程序崩潰)。

更新:在這種情況下,if(&Symbol)檢查,現在是多餘的(除非你真的需要支持出於某種原因的iOS 3)。但是,在使用API​​之前知道這個技術是否有用是很有用的。我更喜歡這種技術,而不是測試操作系統版本,因爲您正在檢查特定的API是否存在,而不是使用外部知識來了解哪些操作系統版本中存在哪些API。

+0

感謝快回答! – 2010-10-04 18:44:36

5

如果實現UIApplicationDelegate,你還可以掛接到充當委託的一部分:

- (void)applicationDidEnterBackground:(UIApplication *)application { 
    /* 
    Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
If your application supports background execution, called instead of applicationWillTerminate: when the user quits. 
    */ 
    NSLog(@"Application moving to background"); 
} 


- (void)applicationWillEnterForeground:(UIApplication *)application { 
    /* 
    Called as part of the transition from the background to the active state: here you can undo many of the changes made on entering the background. 
    */ 
    NSLog(@"Application going active"); 
} 

有關協議的參考看到http://developer.apple.com/library/ios/#documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html