iOS開發:保持程序在後臺長時間運行


轉自:http://www.nivalxer.com/archives/category/ios


iOS爲了讓設備儘量省電,減少不必要的開銷,保持系統流暢,因而對後臺機制採用墓碑式的“假後臺”。除了系統官方極少數程序可以真後臺,一般開發者開發出來的應用程序後臺受到以下限制:
1.用戶按Home之後,App轉入後臺進行運行,此時擁有180s後臺時間(iOS7)或者600s(iOS6)運行時間可以處理後臺操作
2.當180S或者600S時間過去之後,可以告知系統未完成任務,需要申請繼續完成,系統批准申請之後,可以繼續運行,但總時間不會超過10分鐘。
3.當10分鐘時間到之後,無論怎麼向系統申請繼續後臺,系統會強制掛起App,掛起所有後臺操作、線程,直到用戶再次點擊App之後纔會繼續運行。

當然iOS爲了特殊應用也保留了一些可以實現“真後臺”的方法,摘取比較常用的:
1.VOIP
2.定位服務
3.後臺下載
4.在後臺一直播放無聲音樂(容易受到電話或者其他程序影響,所以暫未考慮)
5….更多
其中VOIP需要綁定一個Socket鏈接並申明給系統,系統將會在後臺接管這個連接,一旦遠端數據過來,你的App將會被喚醒10s(或者更少)的時間來處理數據,超過時間或者處理完畢,程序繼續休眠。
後臺現在是iOS7引入的新API,網上實現的代碼比較少,博主也沒有細心去找。
由於博主要做的App需要在後臺一直運行,每隔一段時間給服務器主動發送消息來保持帳號登陸狀態,因而必須確保App不被系統墓碑限制。
博主最先嚐試了很多方法,包括朋友發來的一個Demo,每180s後臺時間過期就銷燬自己然後再創建一個後臺任務,但是實際測試只有10分鐘時間。最後因爲考慮到VOIP對服務端改動太大,時間又太緊,所以選擇了定位服務的方法來保持後臺。

要啓動定位服務:
1.需要引入頭文件:#import <CoreLocation/CoreLocation.h>
2.在AppDelegate.m中定義CLLocationManager * locationManager;作爲全局變量方便控制
3.在程序啓動初期對定位服務進行初始化:

1
2
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;//or whatever class you have for managing location</pre>

4.在程序轉入後臺的時候,啓動定位服務
[locationManager startUpdatingLocation];(第一次運行這個方法的時候,如果之前用戶沒有使用過App,則會彈出是否允許位置服務,關於用戶是否允許,後面代碼中有判斷)
這樣在定位服務可用的時候,程序會不斷刷新後臺時間,實際測試,發現後臺180s時間不斷被刷新,達到長久後臺的目的。

但是這樣使用也有一些問題,在部分機器上面,定位服務即使打開也可能不能刷新後臺時間,需要完全結束程序再運行。穩定性不知道是因爲代碼原因還是系統某些機制原因。

下面貼上代碼:
注意:代碼中包含朋友給的demo中,180s時間後銷燬自己再創建自己的後臺方法,我自己實現過程中加入了定位服務來確保後臺能夠一直在線。
源碼參考部分來自網上,因爲翻了Google,找了很多英文方面的博文,在此感謝原作者分享。

判斷用戶是否打開了定位服務,是否禁用了該程序的定位權限:

1
2
3
4
5
if(![CLLocationManager locationServicesEnabled] || ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied))//判斷定位服務是否打開
    {
        [InterfaceFuncation ShowAlertWithMessage:@"錯誤" AlertMessage:@"定位服務未打開\n保持在線需要後臺定位服務\n請到 設置-隱私 中打開定位服務" ButtonTitle:@"我錯了"];
        return;
    }

AppDelegate.m源碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
@property (assign, nonatomic) UIBackgroundTaskIdentifier bgTask;
 
@property (strong, nonatomic) dispatch_block_t expirationHandler;
@property (assign, nonatomic) BOOL jobExpired;
@property (assign, nonatomic) BOOL background;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
 
 UIApplication* app = [UIApplication sharedApplication];
 
 __weak NSUAAAIOSAppDelegate* selfRef = self;
 
 self.expirationHandler = ^{  //創建後臺自喚醒,當180s時間結束的時候系統會調用這裏面的方法
 [app endBackgroundTask:selfRef.bgTask];
 selfRef.bgTask = UIBackgroundTaskInvalid;
 selfRef.bgTask = [app beginBackgroundTaskWithExpirationHandler:selfRef.expirationHandler];
 NSLog(@"Expired");
 selfRef.jobExpired = YES;
 while(selfRef.jobExpired)
 {
 // spin while we wait for the task to actually end.
 NSLog(@"等待180s循環進程的結束");
 [NSThread sleepForTimeInterval:1];
 }
 // Restart the background task so we can run forever.
 [selfRef startBackgroundTask];
 };
 
 // Assume that we're in background at first since we get no notification from device that we're in background when
 // app launches immediately into background (i.e. when powering on the device or when the app is killed and restarted)
 [self monitorBatteryStateInBackground];
 locationManager = [[CLLocationManager alloc] init];
 locationManager.delegate = self;
 //[locationManager startUpdatingLocation];
 return YES;
}
 
- (void)monitorBatteryStateInBackground
{
 self.background = YES;
 [self startBackgroundTask];
}
 
- (void)applicationDidBecomeActive:(UIApplication *)application
{
 // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
 NSLog(@"App is active");
 [UIApplication sharedApplication].applicationIconBadgeNumber=0;//取消應用程序通知腳標
 [locationManager stopUpdatingLocation];
 self.background = NO;
}
 
- (void)applicationDidEnterBackground:(UIApplication *)application
{
 // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
 // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
 //if([self bgTask])
 if(isLogined)//當登陸狀態才啓動後臺操作
 {
 self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:self.expirationHandler];
 NSLog(@"Entered background");
 [self monitorBatteryStateInBackground];
 }
}
 
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error//當定位服務不可用出錯時,系統會自動調用該函數
{
 NSLog(@"定位服務出錯");
 if([error code]==kCLErrorDenied)//通過error的code來判斷錯誤類型
 {
 //Access denied by user
 NSLog(@"定位服務未打開");
 [InterfaceFuncation ShowAlertWithMessage:@"錯誤" AlertMessage:@"未開啓定位服務\n客戶端保持後臺功能需要調用系統的位置服務\n請到設置中打開位置服務" ButtonTitle:@"好"];
 }
}
 
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations//當用戶位置改變時,系統會自動調用,這裏必須寫一點兒代碼,否則後臺時間刷新不管用
{
 NSLog(@"位置改變,必須做點兒事情才能刷新後臺時間");
 CLLocation *loc = [locations lastObject];
 //NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining];
 //NSLog(@"Background Time Remaining = %.02f Seconds",backgroundTimeRemaining);
 // Lat/Lon
 float latitudeMe = loc.coordinate.latitude;
 float longitudeMe = loc.coordinate.longitude;
}
 
- (void)startBackgroundTask
{
 NSLog(@"Restarting task");
 if(isLogined)//當登陸狀態才進入後臺循環
 {
 // Start the long-running task.
    NSLog(@"登錄狀態後臺進程開啓");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
 // When the job expires it still keeps running since we never exited it. Thus have the expiration handler
 // set a flag that the job expired and use that to exit the while loop and end the task.
    NSInteger count=0;
    BOOL NoticeNoBackground=false;//只通知一次標誌位
    BOOL FlushBackgroundTime=false;//只通知一次標誌位
    locationManager.distanceFilter = kCLDistanceFilterNone;//任何運動均接受,任何運動將會觸發定位更新
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;//定位精度
    while(self.background && !self.jobExpired)
    {
       NSLog(@"進入後臺進程循環");
       [NSThread sleepForTimeInterval:1];
       count++;
       if(count>60)//每60s進行一次開啓定位,刷新後臺時間
       {
          count=0;
          [locationManager startUpdatingLocation];
          NSLog(@"開始位置服務");
          [NSThread sleepForTimeInterval:1];
          [locationManager stopUpdatingLocation];
          NSLog(@"停止位置服務");
          FlushBackgroundTime=false;
       }
       if(!isLogined)//未登錄或者掉線狀態下關閉後臺
       {
          NSLog(@"保持在線進程失效,退出後臺進程");
          [InterfaceFuncation ShowLocalNotification:@"保持在線失效,登錄已被註銷,請重新登錄"];
          [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
          return;//退出循環
       }
       NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining];
       NSLog(@"Background Time Remaining = %.02f Seconds",backgroundTimeRemaining);
       if(backgroundTimeRemaining<30&&NoticeNoBackground==false)
       {
          [InterfaceFuncation ShowLocalNotification:@"向系統申請長時間保持後臺失敗,請結束客戶端重新登錄"];
          NoticeNoBackground=true;
    }
    //測試後臺時間刷新
       if(backgroundTimeRemaining>200&&FlushBackgroundTime==false)
       {
          [[NSNotificationCenter defaultCenter] postNotificationName:@"MessageUpdate" object:@"刷新後臺時間成功\n"];
          FlushBackgroundTime=true;
          //[InterfaceFuncation ShowLocalNotification:@"刷新後臺時間成功"];
       }
    }
    self.jobExpired = NO;
    });
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章