Android Bluetooth communication.

Source: Internet
Author: User

Here we useRFCOMM is a simple serial linear simulation protocol that provides RS232 control and status signals.

That is, a serial port (COM) transmission protocol with a baud rate of BITs and 8 bits. Therefore, mobile phone Bluetooth can communicate with other Bluetooth devices.

Two devices need to establish a server and a server to communicate with each other. After the client connects to the server, it can send and receive data.

Source code: Http://download.csdn.net/detail/menghnhhuan/3901081

 

[HTML] View plaincopyprint?
  1. /* Some constants, representing the name of the server */
  2. Public static final stringProtocol_scheme_l2cap="Btl2cap";
  3. Public static final stringProtocol_scheme_rfcomm="Btspp";
  4. Public static final stringProtocol_scheme_bt_obex="Btgoep";
  5. Public static final stringProtocol_scheme_tcp_obex="Tcpobex";
  6. Private ipvthserversocketMserversocket=Null;
  7. Private serverthreadStartserverthread=Null; // Enable the service thread
  8. Private clientthreadClientconnectthread=Null; // Client connection thread
  9. Private ipvthsocketSocket=Null;
  10. Private delethdeviceDevice=Null;
  11. Private readthreadMreadthread=Null; // Read data thread
  12. Private descrithadapterMblustmthadapter=Descrithadapter. Getdefaadapter adapter (); // Bluetooth adapter
/* Some constants, representing the server name */public static final string protocol_scheme_l2cap = "btl2cap"; public static final string protocol_scheme_rfcomm = "btspp "; public static final string protocol_scheme_bt_obex = "btgoep"; public static final string protocol_scheme_tcp_obex = "tcpobex"; private javasthserversocket mserversocket = NULL; private serverthread startserverthread = NULL; // enable the service thread private clientthread clientconnectthread = NULL; // The client connection thread private javasthsocket socket = NULL; private javasthdevice device = NULL; private readthread mreadthread = NULL; // read the data thread private javasthadapter mblustmthadapter = descrithadapter. getdefaadapter adapter (); // Bluetooth adapter

 

Enable ServerCode

[HTML] View plaincopyprint?
    1. Startserverthread=NewServerthread ();
    2. Startserverthread. Start ();
 
Startserverthread = new serverthread (); startserverthread. Start ();

Enable Client

[HTML] View plaincopyprint?
    1. Device=Mblustmthadapter. Getremotedevice (Address );
    2. Clientconnectthread=NewClientthread ();
    3. Clientconnectthread. Start ();
 
Device = mblustmthadapter. getremotedevice (Address); clientconnectthread = new clientthread (); clientconnectthread. Start ();

Server code

[HTML] View plaincopyprint?
  1. // Enable the server
  2. Private class serverthread extends thread {
  3. Public void run (){
  4. Try {
  5. /* Create a Bluetooth server
  6. * Parameters: Server Name and UUID */
  7. Mserversocket=Mblustmthadapter. Listenusingrfcommwithservicerecord (protocol_scheme_rfcomm,
  8. UUID. fromstring ("20171101-0000-1000-8000-00805f9b34fb "));
  9. Log. D ("server", "Wait cilent connect ...");
  10. /* Accept client connection requests */
  11. Socket=Mserversocket. Accept ();
  12. Log. D ("server", "accept success! ");
  13. // Start receiving data
  14. Mreadthread=NewReadthread ();
  15. Mreadthread. Start ();
  16. } Catch (ioexception e ){
  17. // Todo auto-generated Catch Block
  18. E. printstacktrace ();
  19. }
  20. }
  21. };
// Enable server private class serverthread extends thread {public void run () {try {/* to create a Bluetooth server * parameters: Server Name, UUID */mserversocket = mbluw.thadapter. listenusingrfcommwithservicerecord (protocol_scheme_rfcomm, UUID. fromstring ("20171101-0000-1000-8000-00805f9b34fb"); log. D ("server", "Wait cilent connect... ");/* accept client connection requests */socket = mserversocket. accept (); log. D ("server", "accept success! "); // Start receiving data mreadthread = new readthread (); mreadthread. start ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}};

Client code:

[HTML] View plaincopyprint?
  1. // Enable the client
  2. Private class clientthread extends thread {
  3. Public void run (){
  4. Try {
  5. // Create a socket connection: only the uuid of the server at registration is required.
  6. //Socket=Device. Createrfcommsockettoservicerecord (export thprotocols. obex_object_push_protocol_uuid );
  7. Socket=Device. Createrfcommsockettoservicerecord (UUID. fromstring ("20171101-0000-1000-8000-00805f9b34fb "));
  8. // Connection
  9. Socket. Connect ();
  10. // Start receiving data
  11. Mreadthread=NewReadthread ();
  12. Mreadthread. Start ();
  13. }
  14. Catch (ioexception E)
  15. {
  16. Log. E ("Connect", "", e );
  17. MessageMSG=NewMessage ();
  18. MSG. OBJ="An error occurred while connecting to the server! Disconnect and try again. ";
  19. MSG. What=0;
  20. Linkdetectedhandler. sendmessage (MSG );
  21. }
  22. }
  23. };
 
// Enable Client Private class clientthread extends thread {public void run () {try {// create a socket connection: only the uuid ID of the server at registration/socket = device. createrfcommsockettoservicerecord (fig. obex_object_push_protocol_uuid); socket = device. createrfcommsockettoservicerecord (UUID. fromstring ("20171101-0000-1000-8000-00805f9b34fb"); // connect to the socket. connect (); // start receiving data mreadthread = new readthread (); mreadthread. start ();} Ca Tch (ioexception e) {log. E ("Connect", "", e); message MSG = new message (); msg. OBJ = "An error occurred while connecting to the server! Disconnect and try again. "; MSG. What = 0; linkdetectedhandler. sendmessage (MSG );}}};

Code for sending and receiving data

[HTML] View plaincopyprint?
  1. // Send data
  2. Private void sendmessagehandle (string MSG)
  3. {
  4. If (Socket= NULL)
  5. {
  6. Toast. maketext (mcontext, "No connection", Toast. length_short). Show ();
  7. Return;
  8. }
  9. Try {
  10. OutputstreamOS=Socket. Getoutputstream ();
  11. OS. Write (msg. getbytes ());
  12. } Catch (ioexception e ){
  13. // Todo auto-generated Catch Block
  14. E. printstacktrace ();
  15. }
  16. }
  17. // Read data
  18. Private class readthread extends thread {
  19. Public void run (){
  20. Byte []Buffer=NewByte [2, 1024];
  21. Int bytes;
  22. InputstreamMminstream=Null;
  23. Try {
  24. Mminstream=Socket. Getinputstream ();
  25. } Catch (ioexception E1 ){
  26. // Todo auto-generated Catch Block
  27. E1.printstacktrace ();
  28. }
  29. While (true ){
  30. Try {
  31. // Read from the inputstream
  32. If ((Bytes=Mminstream. Read (buffer ))>0)
  33. {
  34. Byte []Buf_data=NewByte [bytes];
  35. For (intI=0; I<Bytes; I ++)
  36. {
  37. Buf_data [I] = buffer [I];
  38. }
  39. StringS=NewString (buf_data );
  40. MessageMSG=NewMessage ();
  41. MSG. OBJ=S;
  42. MSG. What=1;
  43. Linkdetectedhandler. sendmessage (MSG );
  44. }
  45. } Catch (ioexception e ){
  46. Try {
  47. Mminstream. Close ();
  48. } Catch (ioexception E1 ){
  49. // Todo auto-generated Catch Block
  50. E1.printstacktrace ();
  51. }
  52. Break;
  53. }
  54. }
  55. }
  56. }

 

Source: http://blog.csdn.net/menghnhhuan/article/details/7057484

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.