2013-07-11 16 views
6

iOS應用程序最小化後,我們可以調用該方法嗎?

我們可以在應用程序最小化後調用方法嗎?

例如,5秒後稱爲applicationDidEnterBackground:

我用這個代碼,但test方法不叫

- (void)test 
{ 
    printf("Test called!"); 
} 

- (void)applicationDidEnterBackground:(UIApplication *)application 
{ 
    [self performSelector:@selector(test) withObject:nil afterDelay:5.0]; 
} 
+0

您在** AppDelegate.m文件方法**'applicationWillResignActive'然後'applicationDidEnterBackground'被調用。 – Rohan

+0

謝謝。但是我的意思是,當它在後臺 – Rubinc

+0

看看[如何以編程方式截取iPhone主屏幕](http://stackoverflow.com/q/13459682/593709) –

回答

6

您可以使用後臺任務的API調用一個方法,你已經轉到後臺運行之後(只要你的任務不走太長 - 通常約10分鐘是最大允許時間)。

iOS不讓定時器在應用程序背景時觸發,所以我發現在應用程序後臺調度後臺線程,然後將該線程置於睡眠狀態,具有與定時器相同的效果。

將下面的代碼在應用程序委託的- (void)applicationWillResignActive:(UIApplication *)application方法:

// Dispatch to a background queue 
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ 

    // Tell the system that you want to start a background task 
    UIBackgroundTaskIdentifier taskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ 
     // Cleanup before system kills the app 
    }]; 

    // Sleep the block for 5 seconds 
    [NSThread sleepForTimeInterval:5.0]; 

    // Call the method if the app is backgrounded (and not just inactive) 
    if (application.applicationState == UIApplicationStateBackground) 
     [self performSelector:@selector(test)]; // Or, you could just call [self test]; here 

    // Tell the system that the task has ended. 
    if (taskID != UIBackgroundTaskInvalid) { 
     [[UIApplication sharedApplication] endBackgroundTask:taskID]; 
    } 

}); 
+0

溫尼,它的幫助!謝謝! – Rubinc

+0

不客氣! –

相關問題