首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当应用程序处于非活动状态时监控耳机插孔

当应用程序处于非活动状态时监控耳机插孔
EN

Stack Overflow用户
提问于 2013-02-06 00:19:22
回答 1查看 281关注 0票数 0

我想在我的应用程序中监控耳机插孔,我有这样做的代码,但这只在应用程序处于活动状态时才起作用,即使应用程序处于不活动状态,我也需要这样做。这有可能吗?

在我的测试中,我把用于监控的代码放在AppDelegate中,当我拔出插孔时,它会触发我为这种情况设置的" NSLog“,如果我插上它,另一个NSLog就会启动,但当用户按下”电源按钮“时,我知道我的应用程序现在是”不活动的“,监控代码在当时不起作用。

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

EN

回答 1

Stack Overflow用户

发布于 2013-02-06 03:28:06

在应用程序使用后台任务进入后台后,您可以运行应用程序最多10分钟。看看iOS应用程序编程指南中的Background Execution and Multitasking部分。

代码语言:javascript
复制
- (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通知用户

代码语言:javascript
复制
- (void)notifyUserWhilePerformingBackgroundTask
{
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.alertBody = @"Headphone removed!";

    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14711988

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档