2013-05-14 76 views
0

我需要屏幕開/關回調和語音呼叫回調。但是當我的應用程序處於前臺時,我正在接收回調。但是當我的應用程序處於後臺時,我無法獲得委託回調。如何在我的應用程序處於後臺時獲取阻止或委託回調?防止iPhone應用程序處於不活動狀態

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

閱讀,我發現「Backgound執行和多任務處理」 http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW20

但沒有什麼幫助我這個問題。請幫忙。

+0

您是否在應用程序委託中嘗試了這兩種方法, - (void)applicationWillResignActive:(UIApplication *)application; - (void)applicationDidBecomeActive:(UIApplication *)application; – 2013-05-14 11:54:16

+0

不幸的是,屏幕開/關和電話開始/結束事件不直接提供給應用程序。您必須使用現有的應用程序事件並創建解決方法。 – Amar 2013-05-14 12:33:37

+0

我也嘗試過後臺執行代碼。但它會執行代碼直到線程處於活動狀態。當控制線外出。應用程序沒有響應任何事件(如果應用程序處於後臺模式)。 – 2013-05-14 12:35:54

回答

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

當我的應用程序進入後臺或前臺狀態時,它會給我回調。當我的應用程序在後臺運行時,它不會給我回調。當我的應用程序已經在後臺模式下運行時,我需要委託回調。 – 2013-05-14 12:34:31

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()使應用程序可以在後臺運行三分鐘。

相關問題