我想在我的应用程序中监控耳机插孔,我有这样做的代码,但这只在应用程序处于活动状态时才起作用,即使应用程序处于不活动状态,我也需要这样做。这有可能吗?
在我的测试中,我把用于监控的代码放在AppDelegate中,当我拔出插孔时,它会触发我为这种情况设置的" NSLog“,如果我插上它,另一个NSLog就会启动,但当用户按下”电源按钮“时,我知道我的应用程序现在是”不活动的“,监控代码在当时不起作用。
是否有可能为此目的创建一个即使应用程序处于非活动状态也可以工作的后台任务?
发布于 2013-02-06 03:28:06
在应用程序使用后台任务进入后台后,您可以运行应用程序最多10分钟。看看iOS应用程序编程指南中的Background Execution and Multitasking部分。
- (void)applicationDidEnterBackground:(UIApplication *)application
{
backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{
// clean up any unfinished task business, your app is going to be killed if you don't end the background task now
[application endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}];
// start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Monitor the head phone jack here.
// If this happens asynchronously, you don't need to dispatch this block, your app will continue to run as normal, only modifying or accessing its UI while it's in background mode is prohibited.
// End the background task if you're done. If this is never the case, your expiration handler will be called after ten minutes.
[application endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
});
}您可以通过发送UILocalNotification通知用户
- (void)notifyUserWhilePerformingBackgroundTask
{
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = @"Headphone removed!";
[[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}https://stackoverflow.com/questions/14711988
复制相似问题