2011-07-20 33 views
0

我用下面的代碼我怎麼能自動停止,當應用程序在前臺狀態即將所有後臺任務

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000 
if ([[UIApplication sharedApplication] 
    respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)]) 
{ 
    UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication] 
             beginBackgroundTaskWithExpirationHandler:^{}]; 

    // Perform work that should be allowed to continue in background 
    [self changeCounter]; 
    //[NSThread detachNewThreadSelector:@selector(changeCounter) toTarget:self withObject:_viewController]; 

    [[UIApplication sharedApplication] endBackgroundTask:bgTask]; 
} 
#endif 

changeCounter包含了一段時間後。但如果應用進來前景停止循環之前可能最後一圈那麼我只能看到黑色屏幕直到循環完成。 所以,我怎麼能停止所有任務的應用程序自帶的前景

這是changeCounter

-(void)changeCounter{ 
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; 

while(back==1.0f){ 
    NSLog(@"loop is runnig"); 
    [NSThread sleepForTimeInterval:1.0]; 

if(_viewController.minutes<0){ 

    if(_viewController.fadeSeconds>0){ 
     float div=_viewController.deviceVolume/[_viewController.volumeData.fadeTime floatValue]; 
     _viewController.musicPlayer.volume=_viewController.musicPlayer.volume-div; 
     _viewController.fadeSeconds-=1; 

    } 
    else { 
     [self stop]; 
     //self.musicPlayer.volume=0.0f; 
     // counter=0; 
     NSLog(@"closing the sound"); 
     [_viewController.musicPlayer pause]; 
     NSLog(@"fade seconds %i minutes ",_viewController.fadeSeconds); 
     if(_viewController.dvol==0){ 
      _viewController.musicPlayer.volume=deviceVolume; 
      _viewController.dvol=1; 
     } 
     back=0.0f; 
    }// end of the else 

} 

回答

1

我認爲你的[自changeCounter]方法是在你的應用程序的主線程中運行代碼這就是爲什麼你眼見黑屏直到操作完成。您應該考慮是否適合在主線程上運行該操作,或者是否應將其移至後臺線程。當你回到前臺時,你真的想要完成任務嗎?或者只要UI沒有被鎖定,任務就完成了嗎?

+0

是我想殺了它,因爲當應用程序將變爲活動時,另一個任務將用gui執行 –

+0

發佈代碼[self changeCounter] – jaminguy

+0

請檢查編輯 –

相關問題