我想监听我的应用程序中的耳机插孔,我有代码可以执行此操作,但这只适用于应用程序处于活动状态时,即使应用程序处于非活动状态,我也需要执行此操作。这可能吗?
在我的测试中,我将监控代码放在AppDelegate中,当我拔下插头时,它会触发我为此案例添加的“NSLog”,如果我插入它,则会启动另一个NSLog,但是当用户按下时“电源按钮”我理解,我的应用程序现在处于“非活动状态”,并且监控代码当时不起作用。
是否可以为此目的创建后台任务,即使应用程序处于非活动状态也能正常工作?
答案 0 :(得分:0)
在应用程序使用后台任务进入后台后,您可以运行应用程序最多十分钟。请查看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];
}