I wanted to write this article long ago and I have forgotten it. Before the beginning of the development of Android to engage in Bluetooth development, good head big! Studied for half a month to get it done. Now self-organized Bluetooth development framework, this framework is relatively simple, but hope to help Bluetooth development friends. Of course, personal technology is very food, the shortcomings please guide.
Bluetooth Open step:1. Understand that there are five classes in the Bluetooth API, which need to hold three classes:bluetoothadapter (Bluetooth adapter): This class mainly to obtain Bluetooth information, compared to turn on Bluetooth, get MAC address, paired Bluetooth information, and so on;
Bluetoothdevice (Bluetooth device): If you connect to a non-Android device, this class is mainly the initial server connection Bluetooth (the machine as a client), if the connection to the Android device, to see who first send the connection who is the client;
Bluetoothsocket (Bluetooth communication): If you understand the socket, it is better to understand that when the connection is successful, you can communicate in the afternoon.
Note: Here is not enough to explain, you can go to the official network to understand.
2. Connect2.1 Find the destination MAC address, you can get the Bluetooth address that has been paired from Bluetoothadapter, select the Bluetooth address (MAC) you want to connect to.
2.2 According to the MAC generated objects, by: Bluetoothdevice device = Bluetoothadapter.getdefaultadapter (). Getremotedevice (MAC); Get a bluetoothdevice, which is equivalent to finding the connected object;
2.3 connection, Bluetoothsocket socket = Device.createrfcommsockettoservicerecord (UUID); Connect non-Android device to use fixed UUID:
UUID uuid = uuid.fromstring ("00001101-0000-1000-8000-00805F9B34FB"), if the connection between Android devices is to be customized.
2.4 Initiating the connection, Socket.connect (); Prevents the ANR event from processing the connection asynchronously.
3. CommunicationCommunication from socket available output stream and input stream: stream = Socket.getinputstream (); Output = Socket.getoutputstream ();
It is important to note that when Bluetooth sends data over it is not a one-time can be obtained from the input stream, a piece of data can be sent over several times. So make a buffer!
4. Parse the data, this is nothing to say, according to the protocol to parse the return data (do not know can add me qq:755022831)The following code shows: using:
Package Com.cyy.bluetest;import Android.app.activity;import Android.os.bundle;import android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.textview;import Com.cyy.bluetooth.blueconnethandler;import Com.cyy.bluetooth.bluedevicecontrol;import Com.cyy.bluetooth.bluetoothcallback;public class Mainactivity extends Activity implements Onclicklistener {private TextView tv;private Blueconnethandler handler; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Findviewbyid (R.id.bn). Setonclicklistener (this); TV = (Button) Findviewbyid (r.id.tv);} private void Blue () {Bluedevicecontrol control = new Bluedevicecontrol (); Control.openblue ();//turn on Bluetooth handler = new Blueconn Ethandler (New Bluetoothcallback () {@Overridepublic void getDate (String date) {tv.settext ("Connection data:" + date);} @Overridepublic void Connect (Boolean state) {Tv.settext ("Connection:" + state),}}, "MAC Address"); handler.seNdemptymessage (blueconnethandler.connect);} @Overridepublic void OnClick (View v) {if (Handler.getstateconnect ()! = 0) {Tv.settext ("Already in connection ....");} else {tv.settext ("in connection ....."); Blue ();}}}
Bluedevicecontrol to bluetoothadapter a package:
Package Com.cyy.bluetooth;import Java.util.arraylist;import Java.util.hashmap;import java.util.map;import Java.util.set;import Android.bluetooth.bluetoothadapter;import Android.bluetooth.bluetoothdevice;import Android.content.context;import Android.content.sharedpreferences;public class Bluedevicecontrol {private Bluetoothadapter adapter;/** Construction Method */public Bluedevicecontrol () {adapter = Bluetoothadapter.getdefaultadapter ();} /** whether the device supports Bluetooth */public Boolean isbluetoothsupported () {return adapter! = NULL;} /** Open bluetooth */public void Openblue () {if (adapter! = NULL &&!adapter.isenabled ()) {adapter.enable ()}} /** off bluetooth */public void Closeblue () {if (adapter! = NULL && adapter.isenabled ()) {adapter.disable ()}} /** returns a paired Bluetooth device */public string[] getpartners () {set<bluetoothdevice> Set = Adapter.getbondeddevices (); String list[] = new String[set.size ()];int i = 0;for (Bluetoothdevice device:set) {List[i] = device.getaddress (); i++;} return list;} /** returns a paired Bluetooth device */public arraylist<Map<string, string>> allpartners () {arraylist<map<string, string>> list = new ArrayList<Map <string, string>> (); set<bluetoothdevice> set = Adapter.getbondeddevices (); for (Bluetoothdevice Device:set) {Map<String, String > map = new hashmap<string, string> (), Map.put ("name", Device.getname ()), Map.put ("Address", device.getaddress ()); List.add (map);} return list;} /** automatically connects the last connected Bluetooth address */public String getadress (context context) {sharedpreferences prference; String blue_pref_name = "Blue_pref_name"; String address = "Address";p rference = context.getsharedpreferences (blue_pref_name, 0); String tmp = prference.getstring (ADDRESS, "00:0e:ea:ce:c9:64"); return tmp;} /** Save Bluetooth address, sharedpreferences save */public void saveadress (context context, String Mac) {if (context! = null) {Sharedpreferen CES prference; String blue_pref_name = "Blue_pref_name"; String address = "Address";p rference = context.getsharedpreferences (blue_pref_name, 0);p Rference.edit (). Putstring ( AddreSS, Mac). commit ();}}}
Blueconnectthread Bluetooth Connection Thread:
Package Com.cyy.bluetooth;import Java.io.bufferedinputstream;import Java.io.ioexception;import Java.io.InputStream ; Import Java.io.outputstream;import Java.io.unsupportedencodingexception;import Java.util.uuid;import Android.bluetooth.bluetoothadapter;import Android.bluetooth.bluetoothdevice;import Android.bluetooth.bluetoothsocket;import Android.os.handler;import Android.os.message;public Class Blueconnectthread extends Thread {private Handler handler;//connection non-Android device fixed uuidprivate final uuid uuid = uuid.fromstring ("0000 1101-0000-1000-8000-00805F9B34FB ");p rivate bluetoothdevice device;private bluetoothsocket socket;private OutputStream output;private String mac;public blueconnectthread (Handler Handler) {this.handler = Handler;} @Overridepublic void Run () {InputStream stream;try {socket.connect (); stream = Socket.getinputstream (); output = Socket.getoutputstream (); Bufferedinputstream input = new Bufferedinputstream (stream); Message message = Handler.obtainmessage (Blueconnethandler.connect_succeed, MAC); Message.sendtotarget (); int length;byte[] bytes = new Byte[100];while ((length = input.read (bytes))! =-1) {byte[] ca Chebyte = new Byte[length]; System.arraycopy (bytes, 0, cachebyte, 0, length); message = Handler.obtainmessage (Blueconnethandler.get_data, Cachebyte); Message.sendtotarget ();}} catch (IOException e) {Message message = Handler.obtainmessage (Blueconnethandler.connect_fail); Message.sendtotarget ( ); System.out.println (E.tostring ());}} public boolean sendmsg (String msg) {if (output! = null) {try {output.write (msg.getbytes ("UTF-8")), return true;} catch (Uns Upportedencodingexception e) {System.out.println (e.tostring ());} catch (IOException e) {System.out.println ( E.tostring ());}} return false;} public void Setmac (String mac) {This.mac = mac;try {///judgment is not a valid Bluetooth address if the address is invalid IllegalArgumentException exception device = Bluetoothadapter.getdefaultadapter (). Getremotedevice (MAC);//change socket Channel socket = Device.createrfcommsockettoservicerecord (UUID);} catch (IllegalArgumentException e) {System.out.println (E. toString ());} catch (IOException e) {System.out.println (e.tostring ());}}}
Blueconnethandler Data Processing
Package Com.cyy.bluetooth;import Java.nio.bytebuffer;import Android.os.handler;import android.os.Message;public Class Blueconnethandler extends Handler {private Bluetoothcallback callback;//default, you can customize the test destination MAC address private String mac = "00: 0e:ea:ce:c9:53 ";//buffer 1024 bytes, if you receive more content, you can appropriately increase the buffer private Bytebuffer Bluedata = Bytebuffer.allocate (1024x768);p ublic static Final int CONNECT = 0x111111;public static final int get_data = 0x111111 + 1;public static final int connect_fail = 0x1111 One + 2;public static final int connect_succeed = 0x111111 + 3;private static final int RESET = 0x111111 + 4;private static Final int time = ten * 1000;private int stateconnect = 0;//connection state, default does not start connection private Blueconnectthread thread;public blueconnet Handler (Bluetoothcallback callBack) {this.callback = CallBack;} Public Blueconnethandler (Bluetoothcallback callBack, String mac) {this.callback = Callback;this.mac = Mac;} @Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg); switch (msg.what) {case Connect:if (threAD = = NULL | | !thread.isalive ()) {stateconnect = Connect;thread = new Blueconnectthread (this); Thread.setmac (MAC); Thread.Start ();} Break;case Connect_fail:stateconnect = Connect_fail;dealacallback (false);//set to continue reconnecting after a connection failure Restart this.sendemptymessagedelayed after 10 seconds (CONNECT, time); Break;case connect_succeed:stateconnect = Connect_succeed;mac = ( String) Msg.obj;callback.connect (True);d Ealacallback (True), Break;case get_data://obtains some data from Bluetooth, usually a set of data sent over several times byte[] bytes = (byte[]) msg.obj;bluedata.put (bytes); this.removemessages (reset); this.sendemptymessagedelayed (reset, 100); Break;case RESET://Get a set of data from Bluetooth sent out Decodereset (); break;default:break;}} private void Dealacallback (Boolean isconnect) {if (null! = CallBack) {callback.connect (isconnect);}} The/** resolves the data based on the Bluetooth protocol. Then reset data */private void Decodereset () {bluedata.flip ();//String data = bytes2string (Bluedata.array ());//simply Handle, Specifically, the data is parsed according to the protocol string, a new string (Bluedata.array ()), and if (callBack! = null) {callback.getdate (data);} Bluedata.clear ();} /** 16 binary byte array converted to decimal string */private String bytes2string (byte[] bytes) {Long sum = 0;for (int i = 0; i < bytes.length; i++) {Long cache = Bytes[i ] & 0xff;for (int j = 0; J < i; J + +) {cache = cache << 4 << 4;} sum + = cache;} return sum + "";} public int Getstateconnect () {return stateconnect;} public boolean sendmsg (String msg) {if (thread! = null) {return thread.sendmsg (msg);} return false;}}
Code Open Source Svn:http://code.taobao.org/svn/blueconnect/trunk
CSDN Download
Android Bluetooth Development Open source Framework code case