iOS开发- 蓝牙后台接收数据(BLE4.0)

最近在做一个蓝牙相关的项目, 需要在应用进入后台, 或者手机属于锁屏状态的情况下, 仍然保持蓝牙连接, 并且能正常接收数据。

本来以后会很麻烦, 但是学习了下..发现就2步而已。简单的不能再简单了。


好了。下面是具体实现办法。


1.在xxx-info.plist文件中, 新建一行  Required background modes , 加入下面两项。

App shares data using CoreBluetooth 和 App communicates using CoreBluetooth

如图所示:



加入这个项后, 你会发现, 当应用进入后台后, 蓝牙还是保持连接的。

但是, 进入后台后, 虽然应用还挂着, 能够正常接收数据。但是,  来数据了, 如果需要我们实时响应, 那就要用到推送了。

也就是, 当数据来的时候, 弹出一个提示框, 提示用户来数据了。


2. 设置本地推送

这里的方法写在AppDelegate.m中。  receiveData对应你接收到数据的响应函数。

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. -(void)receiveData:(NSData*)data  
  2. {  
  3.     NSLog(@"收到数据了");  
  4.       
  5.     //收到数据, 设置推送  
  6.     UILocalNotification *noti = [[UILocalNotification alloc] init];  
  7.     if (noti)  
  8.     {  
  9.         //设置时区  
  10.         noti.timeZone = [NSTimeZone defaultTimeZone];  
  11.         //设置重复间隔  
  12.         noti.repeatInterval = NSWeekCalendarUnit;  
  13.         //推送声音  
  14.         noti.soundName = UILocalNotificationDefaultSoundName;  
  15.         //内容  
  16.         noti.alertBody = @"接收到数据了";  
  17.         noti.alertAction = @"打开";  
  18.         //显示在icon上的红色圈中的数子  
  19.         noti.applicationIconBadgeNumber = 1;  
  20.         //设置userinfo 方便在之后需要撤销的时候使用  
  21.         NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];  
  22.         noti.userInfo = infoDic;  
  23.         //添加推送到uiapplication  
  24.         UIApplication *app = [UIApplication sharedApplication];  
  25.         [app scheduleLocalNotification:noti];  
  26.     }  
  27. }  

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #pragma mark - 接收到推送  
  2. - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification  
  3. {  
  4.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"来电提示"  
  5.                                                     message:notification.alertBody  
  6.                                                    delegate:nil  
  7.                                           cancelButtonTitle:@"接听"  
  8.                                           otherButtonTitles:@"挂断",nil];  
  9.     [alert show];  
  10.     //这里,你就可以通过notification的useinfo,干一些你想做的事情了  
  11.     application.applicationIconBadgeNumber -= 1;  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值