Recently in a Bluetooth-related project, need to be in the background of the application, or the phone belongs to the lock screen condition, still keep the Bluetooth connection, and can receive data normally.
Would have been very troublesome, but learned the next. Found just 2 steps. Simple can no longer be simple.
All right. Here are the concrete ways to achieve this.
1. In the Xxx-info.plist file, create a new row Required background modes
, add the following two items.
APP shares data using Corebluetooth
and App communicates using Corebluetooth
:
After adding this entry, you will find that Bluetooth remains connected when the app is in the background.
However, after entering the background, although the application is still hanging, can receive data normally. However, to the data, if we need to respond in real time, it will be used to push.
That is, when the data comes, pop up a prompt box, prompting the user to come to the data.
2. Set up local push
The method here is written in APPDELEGATE.M. The receivedata corresponds to the response function that you receive the data.
-(void) Receivedata: (nsdata*) Data {NSLog (@"We got the data."); //receive data, set pushUilocalnotification *noti =[[Uilocalnotification alloc] init]; if(Noti) {//Setting the time zoneNoti.timezone =[Nstimezone Defaulttimezone]; //set the recurrence intervalNoti.repeatinterval =Nsweekcalendarunit; //Push SoundNoti.soundname =Uilocalnotificationdefaultsoundname; //contentNoti.alertbody =@"received the data."; Noti.alertaction=@"Open"; //The number of the red circle displayed on the iconNoti.applicationiconbadgenumber =1; //Setup UserInfo is convenient to use when you need to undo laterNsdictionary *infodic = [Nsdictionary dictionarywithobject:@"name"Forkey:@"Key"]; Noti.userinfo=Infodic; //add push to UIApplicationUIApplication *app =[UIApplication sharedapplication]; [App Schedulelocalnotification:noti]; } }
#pragmaMark-received a push-(void) Application: (UIApplication *) application didreceivelocalnotification: (uilocalnotification*) Notification {Uialertview*alert = [[Uialertview alloc] Initwithtitle:@"Call Prompt"Message:notification.alertBody Delegate: nil Cancelbuttontitle:@"Answer"Otherbuttontitles:@"Hanging off", nil]; [Alert show]; //here, you can go through notification's useinfo and do what you want to do.Application.applicationiconbadgenumber-=1; }
iOS Development-Bluetooth backend receive data (BLE4.0)