[英]Keep an iOS app running in foreground
我想知道是否有辦法讓應用程序在特定的間隔時間內保持在前台運行。
我有一個線程正好在3分鍾內運行,我需要用戶不能離開應用程序。 如果這樣的事情不可能,我會問另一個問題。
我可以讓用戶在后台模式下設置應用程序,因為我使用applicationDidEnterBackground:(UIApplication *)application
方法來保存我需要的數據,但如果用戶單擊電源按鈕,我該如何保存數據?
applicationWillTerminate:(UIApplication *)application
將被調用? 有什么解決方案嗎?
您可能希望查看beginBackgroundTaskWithExpirationHandler
,它可以讓您的應用請求額外的處理時間來完成應用程序后台運行時的任務。
也就是說,你想做的事情是不可取的。 您應該確保您的應用可以在意外終止或失敗的情況下從您的三分鍾任務中恢復。 例如,您的應用程序可能會意外崩潰或因內存不足而終止 - 在這些情況下,您將無法獲得對applicationWillTerminate
或applicationDidEnterBackground
任何回調。
因此,我建議使用iOS的后台任務支持,以便在用戶離開應用程序時在后台繼續保存,同時還要確保在系統終止您的應用程序而不發出警告時您的任務可以恢復/可以安全地倒回來。
您需要使用beginBackgroundTaskWithExpirationHandler
來處理您的進程。 使用此代碼。
這里我從applicationDidEnterBackground調用此方法:( UIApplication *)應用程序將數據存儲在SQlite中,即使應用程序輸入后台或UIApplicationStateInactive(按下電源按鈕)。 如果application.backgroundTimeRemaining變為0,保存過程將按照IOS標准繼續保持10分鍾。我將發布一個本地通知,將我的應用程序調到前台以保持我的進程活着。 使用此代碼並自定義您的過程。
-(void)handleBackgroundSavingingProcess:(UIApplication *)application
{
NSLog(@"background task remaining time before background %f",application.backgroundTimeRemaining);
if ((([application applicationState] == UIApplicationStateBackground) || ([application applicationState] == UIApplicationStateInactive)) && [application respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)])
{
self.bgTaskId = [application beginBackgroundTaskWithExpirationHandler:^{
// Synchronize the cleanup call on the main thread in case
// the task actually finishes at around the same time.
NSLog(@"background task remaining time in expiration handler %f",application.backgroundTimeRemaining);
dispatch_queue_t concurrentQueue;
if([[[UIDevice currentDevice] systemVersion] doubleValue] >= 5.0)
concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0UL);
else
concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0UL);
if (concurrentQueue == nil)
return;
dispatch_async(concurrentQueue, ^{
if (self.bgTaskId != UIBackgroundTaskInvalid){
NSLog(@"background task remaining time in dispatch queue %f",application.backgroundTimeRemaining);
NSLog(@" Downloading status %d",self.isDownloadingInComplete);
if(self.isDownloadingInComplete)
{
[application presentLocalNotificationNow:localNotification];
NSLog(@"Local notification fired.");
}
[DataManager managedObjectContext] save:nil];
[application endBackgroundTask:self.bgTaskId];
self.bgTaskId = UIBackgroundTaskInvalid;
NSLog(@"Initialization invalid.");
}
});
}];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.