0

我想监控我的应用程序中的耳机插孔,我有执行此操作的代码,但这仅在应用程序处于活动状态时才有效,即使应用程序处于非活动状态,我也需要这样做。那可能吗?

在我的测试中,我将用于监视的代码放在 AppDelegate 中,当我拔下插孔时,它会触发我为这种情况放置的“NSLog”,如果我插入它,则会启动另一个 NSLog,但是当用户按下“电源按钮”时” 据我了解,我的应用程序现在处于“非活动状态”,并且监控代码当时无法正常工作。

是否有可能为此目的创建一个后台任务,即使应用程序处于非活动状态也可以工作?

4

1 回答 1

0

在应用程序进入后台后,您可以使用后台任务运行应用程序长达十分钟。查看 iOS App Programming Guide 的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];
}
于 2013-02-05T19:28:05.923 回答