我怎么可以检测应用刚从"背景模式"?我的意思是,我不想我的应用程序的获取数据(每60秒)当用户按"家按钮"。但是,我想作一些"特别"的更新第一次应用程序是在前景模式。

我怎么可以检测到这两个活动:

  1. 程序要背景模式
  2. 程序要的前景模式

在此先感谢。

弗朗索瓦*

有帮助吗?

解决方案

这怎么听到这样的事件:

// 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) 检查确保你的代码的工作iOS4.0+并且还在iOS3.x-如果你建立对iOS4.x或5。x SDK和设置的部署目标来iOS3.x你的应用仍然可以运行3.x设备,但该地址相关的符号将为零,并因此它不会尝试要求的通知的,不存在对3.x设备(它会崩溃的应用程序).

更新: 在这种情况下, if(&Symbol) 检查现在是多余的(除非你 真的 需要支持iOS3由于某种原因).然而,它知道这种技术检查,如果一个API存在使用之前。我喜欢这种技术比测试操作系统版本,因为你正在检查,如果具体API是本而不是使用外部知识的什么Api存在什么操作系统版本。

其他提示

如果实现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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top