2011-05-11 154 views
2

似乎我在iOS應用程序中的多任務處理有問題。 我有一個NSTimer正在運行,它會更新屏幕上的一些內容,另一個NSTimer將在定義的時間間隔後僅被觸發一次。應用程序後的黑色屏幕WillEnterForeground

問題是:我想對那個火災事件做出反應。無論我的App是否在前臺。

我用下面的代碼能夠跟蹤定時器:

-(void)backgroundThreadStarted { 
    NSAutoreleasePool* thePool = [[NSAutoreleasePool alloc] init]; 

    // create a scheduled timer 
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(backgroundThreadFire:) userInfo:nil repeats:YES]; 
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; 

    m_isBackgroundThreadToTerminate = NO; 

    // create the runloop 
    double resolution = 300.0; 
    BOOL isRunning; 
    do { 
    // run the loop! 
    NSDate* theNextDate = [NSDate dateWithTimeIntervalSinceNow:resolution]; 
    isRunning = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:theNextDate]; 
    // occasionally re-create the autorelease pool whilst program is running 
    [thePool release]; 
    thePool = [[NSAutoreleasePool alloc] init];    
    } while(isRunning==YES && m_isBackgroundThreadToTerminate==NO); 

    [thePool release]; 
} 

-(void)backgroundThreadFire:(id)sender { 
    // do repeated work every one second here 

    // when thread is to terminate, call [self backgroundThreadTerminate]; 

} 

-(void)backgroundThreadTerminate { 
    m_isBackgroundThreadToTerminate = YES; 
    CFRunLoopStop([[NSRunLoop currentRunLoop] getCFRunLoop]); 
} 

(這裏找到:http://www.cocoadev.com/index.pl?RunLoop

,我號召- (void)applicationWillEnterForeground:(UIApplication *)applicationbackgroundThreadStarted-(void)applicationDidEnterBackground:(UIApplication *)applicationbackgroundThreadTerminate和我能夠跟蹤定時器。所以這個效果很好。

不幸的是,回到應用程序後,整個屏幕是黑色的。我嘗試了不同的解決方案,我搜索了很多,但都沒有成功。

如果我在看到這個黑屏時將應用程序最小化,我可以在動畫到背景時看到該應用程序。

我錯過了什麼?

如果我不做這個backgroundThread的東西,屏幕顯示正常。但之後,我無法跟蹤計時器。

在此先感謝!

+0

你在那個線程上做了什麼樣的工作? – 2011-05-11 18:20:55

+0

只需等待定時器啓動。然後保存一些設置並停止播放音頻 - 這就是計劃。 – ChaosCoder 2011-05-12 08:53:29

回答

2

您正在使用AppKit(OS X)而不是UIKit(iOS)的代碼。

你應該尋找到backgrounding API將涉及處理didEnterBackground,並在那裏建立與beginBackgroundTaskWithExpirationHandler後臺任務:

背景線程是沒有必要的(他們是在後臺運行的東西你的應用程序,而你的應用程序仍在運行)。背景任務是在應用程序不再處於前臺時讓您的常規應用程序代碼運行(無需UI交互)的一種方法。在本地通知服務之外,您將無法輕鬆地與用戶溝通(API更適合在離開應用程序後完成上傳)。並且你的任務被限制在黑暗背景下十分鐘之內。

+0

好的,所以我想要做的就是倒計時計時器,在他被解僱後做些事情,無論應用程序是否在前臺。 一個例子是蘋果的標準clock.app。您可以在定時器啓動後設置動作(例如,暫停iPhone或播放旋律)。他們是怎麼做到的? – ChaosCoder 2011-05-12 08:50:28

+0

蘋果是唯一可以做到這一點的產品(在非越獄設備上)。不幸的是,他們不讓App Store應用程序執行此操作。 – BarrettJ 2011-05-12 17:41:55

+0

所以沒有機會做某事。像那樣?特別糟糕... :/ – ChaosCoder 2011-05-13 11:36:52