【问题标题】:Monitor the headphone jack when the app is inactive当应用程序处于非活动状态时监控耳机插孔
【发布时间】:2013-01-20 15:25:47
【问题描述】:

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

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

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

【问题讨论】:

  • 您可以为此使用后台任务,但任何后台任务将在最多 10 分钟后终止,您的应用可以吗?
  • 当您的应用返回前台时检查耳机插孔的状态。
  • 感谢您的回答; @FabianKreiser 可能可行,但我不太了解“后台任务”,每次拔下耳机插孔时我都需要启动通知,后台任务可能吗?
  • @rmaddy:出于我的目的,这不起作用,因为即使我的应用程序至少有几分钟不活动,我也想做监控。
  • 您可以在应用处于后台时使用 UILocalNotification 触发通知。您将能够监控耳机插孔十分钟并在此期间发出通知,我将在明天发布更详细的答案。

标签: iphone ios background monitoring headphones


【解决方案1】:

在应用进入后台后,您最多可以使用后台任务运行应用十分钟。查看 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];
}

【讨论】:

  • 非常感谢,我试试,我只是不明白“清理任何未完成的任务业务,你的应用不结束后台就会被杀死”的部分现在任务”...哪个“后台任务”?如果当时App没有任何后台任务
  • 这在过期处理程序块内。该块将在十分钟后调用,并且您还没有结束后台任务。
猜你喜欢
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 2013-05-08
  • 2020-01-26
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
相关资源
最近更新 更多