以前有作一個定位的項目,相似嘀嘀打車那樣。 須要後臺持續定位。html
這裏選擇了百度地圖,不過在後臺持續定位方面, 以前只是簡單的設置以下:java
不過經測試發現, 這樣設置完,在後臺運行大概30分鐘,又會被crash掉。 從新打開應用則自動恢復定位。< 喎�"http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD48cD48YnIgLz48L3A+PHA+tbHIu6Os1eKyu8rHztLDx8/r0qq1xNCnufujrMv50tTV28zawcvPwqOsyrXP1sHLuvPMqLPW0Pi2qM67oaM8L3A+PHA+19y1xMC0y7WjrL7NysfA+9PDvfjI67rzzKi6887Sw8e/ybLZv9i1xDEwt9bW06OswLTN6rPJ0rvQqcrCx+mhozwvcD48cD7OqrTvtb2z1tD4tqjOu6Osw78xMLfW1tOho9fUtq/W2NDCv6rG9Laozruho9Xi0fm+zb3ivvbOysziwcuhozwvcD48cD48YnIgLz48L3A+PHA+vt/M5cjnz8I6PC9wPjxwPjxiciAvPjwvcD48cD5BcHBEZWxlZ2F0ZS5oPGJyIC8+PC9wPjxwPjxwcmUgY2xhc3M9"brush:java;">@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier bgTask;
AppDelegate.m
ios
?app
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
|
- (
void
)backgroundHandler
{
NSLog(@
"### -->backgroundinghandler"
);
UIApplication* app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
0
), ^{
// 您想作的事情,
// 好比我這裏是發送廣播, 從新激活定位
// 取得ios系統惟一的全局的廣播站 通知中心
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
//設置廣播內容
NSDictionary *dict = [[NSDictionary alloc]init];
//將內容封裝到廣播中 給ios系統發送廣播
// LocationTheme頻道
[nc postNotificationName:@
"LocationTheme"
object:self userInfo:dict];
});
}
|
?async
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
- (
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.
BOOL backgroundAccepted = [[UIApplication sharedApplication] setKeepAliveTimeout:
600
handler:^{ [self backgroundHandler]; }];
if
(backgroundAccepted)
{
NSLog(@
"backgrounding accepted"
);
}
[self backgroundHandler];
}
|
而後在開啓定位的位置,成爲廣播接收者,而且從新激活定位函數
?post
1
2
3
4
5
|
//初始化BMKLocationService
myLocService = [[BMKLocationService alloc]init];
myLocService.delegate = self;
//啓動LocationService
[myLocService startUserLocationService];
|
?測試
1
2
3
4
|
NSNotificationCenter *nc2 = [NSNotificationCenter defaultCenter];
// 成爲聽衆一旦有廣播就來調用self recvBcast:函數
[nc2 addObserver:self selector:
@selector
(activeLocation:) name:@
"LocationTheme"
object:nil];
|
?ui
1
2
3
4
5
6
7
8
9
|
- (
void
) activeLocation:(NSNotification *)notify
{
[myLocService stopUserLocationService];
//初始化BMKLocationService
myLocService = [[BMKLocationService alloc]init];
myLocService.delegate = self;
//啓動LocationService
[myLocService startUserLocationService];
}
|
固然,上面的方式,可能方法比較渣,代碼也寫的比較亂。this
只是提供一種解決辦法而已。