近期在做一個藍牙相關的項目, 須要在應用進入后台, 或者手機屬於鎖屏狀態的情況下, 仍然保持藍牙連接, 而且能正常接收數據。
本來以后會非常麻煩, 可是學習了下..發現就2步而已。簡單的不能再簡單了。
好了。
以下是詳細實現辦法。
1.在xxx-info.plist文件里, 新建一行 Required background modes , 增加以下兩項。
App shares data using CoreBluetooth 和 App communicates using CoreBluetooth
如圖所看到的:
增加這個項后, 你會發現, 當應用進入后台后, 藍牙還是保持連接的。
可是, 進入后台后, 盡管應用還掛着, 可以正常接收數據。可是, 來數據了, 假設須要我們實時響應, 那就要用到推送了。
也就是, 當數據來的時候, 彈出一個提示框, 提示用戶來數據了。
2. 設置本地推送
這里的方法寫在AppDelegate.m中。 receiveData相應你接收到數據的響應函數。
-(void)receiveData:(NSData*)data { NSLog(@"收到數據了"); //收到數據, 設置推送 UILocalNotification *noti = [[UILocalNotification alloc] init]; if (noti) { //設置時區 noti.timeZone = [NSTimeZone defaultTimeZone]; //設置反復間隔 noti.repeatInterval = NSWeekCalendarUnit; //推送聲音 noti.soundName = UILocalNotificationDefaultSoundName; //內容 noti.alertBody = @"接收到數據了"; noti.alertAction = @"打開"; //顯示在icon上的紅色圈中的數子 noti.applicationIconBadgeNumber = 1; //設置userinfo 方便在之后須要撤銷的時候使用 NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"]; noti.userInfo = infoDic; //增加推送到uiapplication UIApplication *app = [UIApplication sharedApplication]; [app scheduleLocalNotification:noti]; } }
#pragma mark - 接收到推送 - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"來電提示" message:notification.alertBody delegate:nil cancelButtonTitle:@"接聽" otherButtonTitles:@"掛斷",nil]; [alert show]; //這里,你就行通過notification的useinfo。干一些你想做的事情了 application.applicationIconBadgeNumber -= 1; }