first, the use of Bluetooth in Android to develop the class and execution process
1, use Bluetoothadapter.startlescance to scan the device
2. Get the Bluetoothdevice object in the callback function scanned to the device and use Bluetooth.stoplescan to stop scanning
3, use Bluetoothdevice.connectgatt to get to Bluetoothgatt object
4, execute Bluetoothgatt.discoverservices, this method is an asynchronous operation, in the callback function onservicesdiscovered get status, by judging whether the status equals Bluetoothgatt.gatt _success to determine if the service was successful
5, if successful, through Bluetoothgatt.getservice to get Bluetoothgattservice
6, then get bluetoothgattcharacteristic through Bluetoothgattservice.getcharacteristic
7, then get Bluetoothgattdescriptor through Bluetoothgattcharacteristic.getdescriptor
second, send and receive data sent and received by Gatt,gatt is a protocol to send and receive data via Bluetooth, including Characteristic,descriptor,service three attribute values, BLE is divided into three parts Service, Charac Teristic, descriptor these three parts are made up of UUID as a unique identifier, a Bluetooth terminal can contain multiple service, a service can contain multiple characteristic, a characteristic Contains a value and multiple descriptor, and a descriptor contains a value
Third, the code (some of the tools are in other files, I do not change here, directly copied up) Mainactivice.java:
Bluetoothmanager Bluetoothmanager;
Mbluetoothadapter;
Intent ();
Low power bluetooth filename
"Com.boe.navapp.remote.BluetoothLeService";
= (Bluetoothmanager) mainactivity. this
. Getsystemservice (Context. Bluetooth_service);
bluetoothmanager. Getadapter ();
(mbluetoothadapter. IsEnabled ()) {
(! ( Commonutil.isservicerunning (mainactivity. this,
constants.bluetoothservice)) {
Intent (mainactivity. this,
bluetoothleservice. Class);
StartService (intentbluetoothleservice);
}
}
Determines whether the current service starts
isservicerunning (Context mcontext, String className) {
false;
Activitymanager Activitymanager = (activitymanager) mcontext
. Getsystemservice (Context. Activity_service);
list<activitymanager.runningserviceinfo> servicelist = Activitymanager
. getrunningservices ();
(!( Servicelist.size () > 0)) {
return false;
}
(i = 0; i < servicelist.size (); i++) {
(Servicelist.get (i). Servicetrue) {
true;
break;
}
}
isrunning;
}
Bluetoothleservice.java: (I'm going to tell you the main code, the file I'll pass up)
"Remote_connect_status";//Current selected remote connection status
"Remoteconnecteddevices";//store List of connected devices
"Remotedeviceinfo";
"Remotecurraddr";//Address of the current connected device
"Com.infisight.hudprojector.bluetooth.le.ACTION_GATT_REMOTESEVEN_DISCONNECTED";
"Address";
@Override
onCreate () {
Super. OnCreate ();
LOGTOOLS.I (TAG"Bluetoothleservice onCreate");
= preferencemanager.getdefaultsharedpreferences (this);
= (telephonymanager) getsystemservice (telephony_service);
prefs. Edit (). Putboolean (Constants. Remote_connect_statusfalse)
. commit ();
LOGTOOLS.I (TAG"Bluetoothleservice before Saveutils.loadarray");
= Saveutils.loadarray (thissp_name); Address of the storage connection
getdeviceinfo ();
LOGTOOLS.I (TAG"Bluetoothleservice getdeviceinfo");
}
/** * get device information lstneedconnectdevices */private voidGetdeviceinfo () {String Connectedinfo =prefs. getString (Constants.remote_connected_devices,"");if(!connectedinfo.equals ("") {Gson Gson =NewGson ();Try{lstneedconnectdevices= Gson.fromjson (Connectedinfo,NewTypetoken<list<bleconnectdevice>> () {}.gettype ()); for(Bleconnectdevice Bleconnectdevice:lstneedconnectdevices) {if(!lstneedconnectaddress. Contains (Bleconnectdevice. getaddress ()))lstneedconnectaddress . Add (Bleconnectdevice.getaddress ()); }
}Catch(Exception e) {
}
}
}
Initialize () {
//Get Bluetooth Management
(null) {
= (Bluetoothmanager) Getsystemservice (Context. Bluetooth_service);
(null) {
return false;
}
}
Gets the adapter
mbluetoothmanager. Getadapter ();
null ;
}
@Overridepublic intOnstartcommand (Intent Intent,intFlagsintStartid) {LOGTOOLS.D (TAG,"onstartcommand:flags="+ Flags +", startid="+ Startid);if(Mbluetoothmanager==NULL) {if(!initialize ()) {LOGTOOLS.I (TAG,"Unable to initialize Bluetooth"); }
}if(IsFirstRun) {Try{Handler. postdelayed (runnable, 2000); }Catch(Exception e) {
}
}Else{LOGTOOLS.I (TAG,"Constants.remote_device_info:"); String address = getsharedpreferences (Constants.Remote_device_info, 0). getString (Constants.remote_curr_addr,"0");
Connect (address); }IsFirstRun=false;returnStart_sticky; }
/**
* Start connection thread
*/Runnable ()
{
@Override Run () {
//start connection here, If the connection fails, try connecting logtools.i again
(TAG"Try connect runnable");
{
mbluetoothadapter. Stoplescan (mlescancallback);
mbluetoothadapter. Startlescan (mlescancallback); Scan low power Bluetooth device
(Exception e) {
TODO auto-generated catch block
LOGTOOLS.I (TAG+ e.getmessage ());
E.printstacktrace ();
}
handler. postdelayed (this, 10000);
}
;
The device lookup callback gets the Bluetoothdevice object LescancallbackMlescancallback=NewLescancallback () {@OverridePublic voidOnlescan (FinalBluetoothdevice device,intRssibyte[] scanrecord) {LOGTOOLS.D (TAG,"Device.getname:"+ device.getname () +", device.address:"+ device.getaddress ());if("Keyctrl". Equals (Device.getname ())) {Close (Mgattmap. Get (Device.getaddress ())); Get Bluetoothgatt object Bluetoothgatt Mbluetoothgatt = Device.connectgatt (bluetoothleservice . This,false,Mgattcallback);Mgattmap. Put (Device.getaddress (), Mbluetoothgatt); }else if("Infisight_r". Equals (Device.getname ())//Connect to the Bluetooth OBD function {Try{Close (Mgattmap. Get (Device.getaddress ())); Bluetoothgatt Mbluetoothgatt = Device.connectgatt (bluetoothleservice. This,false,Mgattcallback);Mgattmap. Put (Device.getaddress (), Mbluetoothgatt); }Catch(Exception e) {LOGTOOLS.E (TAG,"Mbluetoothgatt failed:"+ e.getmessage ()); }
}
}
};
Private FinalBluetoothgattcallbackMgattcallback=NewBluetoothgattcallback () {@OverridePublic voidOnconnectionstatechange (Bluetoothgatt GATT,intStatusintNewState) {//Connection status changed String Intentaction = Constants.action_gatt_remoteseven_disconnected; LOGTOOLS.E (TAG,"Onconnectionstatechange:name:"+ Gatt.getdevice (). GetName () +"ADDR:"+ Gatt.getdevice (). GetAddress () +", NewState:"+ newstate);if(NewState = = Bluetoothprofile.state_connected) {hmisconnected. Put (Gatt.getdevice (). GetAddress (),true); Saveutils.savearray (Bluetoothleservice. This,Sp_name,AddressList);if("Keyctrl". Equals (Gatt.getdevice (). GetName ())) {intentaction = Constants.action_gatt_remote_connected; }else if("Infisight_r". Equals (Gatt.getdevice (). GetName ())) {LOGTOOLS.E (TAG,"ble action_gatt_remote_connected"); Intentaction = Constants.action_gatt_remoteseven_connected; }prefs. Edit (). Putboolean (Constants.Remote_connect_status,true). commit ();
Broadcastupdate (intentaction); LOGTOOLS.E (TAG,"ble gatt.discoverservices");
Gatt.discoverservices ();
Savedeviceinfo (Gatt.getdevice ()); }else if(NewState = = Bluetoothprofile.state_disconnected) {LOGTOOLS.D (TAG,"bluetoothprofile.state_disconnected"); Open thread, constantly trying to connect the devicehmisconnected. Put (Gatt.getdevice (). GetAddress (),false);if("Keyctrl". Equals (Gatt.getdevice (). GetName ())) {intentaction = Constants.action_gatt_remote_disconnected; }else if("Infisight_r". Equals (Gatt.getdevice (). GetName ())) {LOGTOOLS.D (TAG,"BLE bluetoothprofile.state_disconnected"); Intentaction = Constants.action_gatt_remoteseven_disconnected; }prefs. Edit (). Putboolean (Constants.Remote_connect_status,false). commit ();
Close (GATT);
Disconnect (GATT);
Broadcastupdate (intentaction); }}//If the status is equal to Bluetoothgatt.gatt_success to determine if the lookup service was successful @OverridePublic voidOnservicesdiscovered (Bluetoothgatt GATT,intStatus) {//Discovery service Broadcast LOGTOOLS.E (TAG,"onservicesdiscovered:"+ Gatt.getdevice (). getaddress ());if(Status = = Bluetoothgatt.gatt_success) {Displaygattservices (Getsupportedgattservices (GATT), GATT); Broadcastupdate (Constants.action_gatt_services_discovered); }} @OverridePublic voidOncharacteristicread (Bluetoothgatt GATT, Bluetoothgattcharacteristic characterist IcintStatus) {LOGTOOLS.D (TAG,"Oncharacteristicread");