As a result of recent project requirements debugging Android Bluetooth communication interface, mainly two terminals as the server and client communications, this article will be some important points of knowledge recorded as follows.
Bluetooth is a short-range wireless communication, usually divided into classic Bluetooth and low-power Bluetooth (that is, Bluetooth 4.0), the two types of Bluetooth protocol layer definitions are many different, so the chip is not the same, but on the Android application layer development is no different.
Bluetooth communication is divided into two parts of pairing and data transmission, the two parts are independent, in general, point to point, if you want to group LAN to support LAN protocol extension, have not tried.
Mbluetoothadapter = bluetoothadapter.getdefaultadapter (); Mbluetoothadapter.enable (); New Intentfilter (); Intent.addaction (bluetoothdevice.action_found); // use Broadcastreceiver to get search results new Bluetoothreceiver (); Registerreceiver (receiver, intent); //Register a broadcast to receive messages from Bluetooth device discovery Mbluetoothadapter.startdiscovery ();
Private classBluetoothreceiverextendsBroadcastreceiver {@Override Public voidOnReceive (Context context, Intent Intent) {String action=intent.getaction (); if(BluetoothDevice.ACTION_FOUND.equals (ACTION)) {if(Isfound = =true){ return; } isfound=true; Bluetoothdevice Bluetoothdevice= Intent.getparcelableextra (Bluetoothdevice.extra_device);//Get this Bluetooth device, there may be multiple
-
- The party being discovered
New Intent ( bluetoothadapter.action_request_discoverable); Discoveryintent.putextra (bluetoothadapter.extra_discoverable_duration );//Popup a window, Confirm that the native Bluetooth device can be found within 300s discoveryintent.setflags (intent.flag_activity_new_task); StartActivity (discoveryintent);
Communication phase is basically equivalent to socket programming, this article does not stick all the code, the only problem is not the reflection method to obtain the device, communication connection is very unstable, this article code is as follows:
New class[]{int. Class= (bluetoothserversocket) Listenmethod.invoke (Adapter, integer.valueof (1= Mmserversocket.accept ();
Method method = Mserverdevice.getclass (). GetMethod ("Createrfcommsocket",newint. Class= (bluetoothsocket) method.invoke (Mserverdevice, integer.valueof (1));
Android (Bluetooth)