防止iPhone应用程序处于非活动状态

时间:2013-05-14 11:51:42

标签: ios iphone objective-c cocoa-touch

我需要屏幕ON / OFF回叫和语音呼叫回调。但是当我的应用程序处于前台时,我正在收到回调。但是当我的应用程序处于后台时,我无法获得委托回调。当我的应用程序处于后台时,如何才能阻止或委托回调?

我通读了苹果文件 http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html

我找到了#34; Backgound执行和多任务处理" http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW20

但是没有什么可以帮助我解决这个问题。请帮忙。

2 个答案:

答案 0 :(得分:0)

尝试使用UILocaleNotification。它可以在系统中注册通知,并可以在指定的时间实现。

    -(void) viewDidLoad{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enteredBackground:) name:@"didEnterBackground" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enteredForeground:) name:@"didEnterForeground" object:nil];
}
 - (void) enteredBackground:(NSNotification*)notification{

        self.notification = [[UILocalNotification alloc] init];

//set the notification property

        [[UIApplication sharedApplication] scheduleLocalNotification:self.notification];


    }


 }
    - (void) enteredForeground:(NSNotification*)notification{
                   //do something
 [[UIApplication sharedApplication] cancelLocalNotification:self.notification];
        }
    } 

在AppDelegate.m中

    - (void)applicationDidEnterBackground:(UIApplication *)application
{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"didEnterBackground" object:nil];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [[NSNotificationCenter defaultCenter] postNotificationName:@"didEnterForeground" object:nil];
}

答案 1 :(得分:0)

您可以在后台模式下运行应用程序3分钟,所有代码都可以运行

 func registerBackgroundTask() {
            backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
                self?.endBackgroundTask()
            }
            assert(backgroundTask != UIBackgroundTaskInvalid)
        }
        func endBackgroundTask() {
            print("Background task ended.")
            UIApplication.shared.endBackgroundTask(backgroundTask)
            backgroundTask = UIBackgroundTaskInvalid
        }

只需调用self.registerBackgroundTask()即可让应用程序在后台运行三分钟。