嘗試使用UILocaleNotification。它可以在系統中註冊一個通知,並且可以在指定的時間執行。
-(void) viewDidLoad{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enteredBackground:) name:@"didEnterBackground" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enteredForeground:) name:@"didEnterForeground" object:nil];
}
- (void) enteredBackground:(NSNotification*)notification{
self.notification = [[UILocalNotification alloc] init];
//set the notification property
[[UIApplication sharedApplication] scheduleLocalNotification:self.notification];
}
}
- (void) enteredForeground:(NSNotification*)notification{
//do something
[[UIApplication sharedApplication] cancelLocalNotification:self.notification];
}
}
在AppDelegate.m
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"didEnterBackground" object:nil];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
[[NSNotificationCenter defaultCenter] postNotificationName:@"didEnterForeground" object:nil];
}
您是否在應用程序委託中嘗試了這兩種方法, - (void)applicationWillResignActive:(UIApplication *)application; - (void)applicationDidBecomeActive:(UIApplication *)application; – 2013-05-14 11:54:16
不幸的是,屏幕開/關和電話開始/結束事件不直接提供給應用程序。您必須使用現有的應用程序事件並創建解決方法。 – Amar 2013-05-14 12:33:37
我也嘗試過後臺執行代碼。但它會執行代碼直到線程處於活動狀態。當控制線外出。應用程序沒有響應任何事件(如果應用程序處於後臺模式)。 – 2013-05-14 12:35:54