最近在做一個藍牙相關的項目, 需要在應用進入后臺, 或者手機屬于鎖屏狀態的情況下, 仍然保持藍牙連接, 并且能正常接收數據。
本來以后會很麻煩, 但是學習了下..發現就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;??
- }?