2nd Bluetooth communications: Establish communications and send text messages, file messages, and 2nd text messages

Source: Internet
Author: User

2nd Bluetooth communications: Establish communications and send text messages, file messages, and 2nd text messages

I. Introduction

When the two android devices are connected normally, you need to enable a server and a client to receive messages (similar to a socket) by searching for and connecting articles here (Bluetooth search and connection ), the two devices must be associated with the same communication ID, usually a uuid. Example: 20171101-0000-1000-8000-00805f9b34fb

Ii. Create a Bluetooth server

1) In the paired Bluetooth list, select the bluetooth device for communication.

BondDevicesListView. setOnItemClickListener (new AdapterView. OnItemClickListener () {@ Override public void onItemClick (AdapterView <?> Parent, View view, int position, long id) {mbluw.thadapter. cancelDiscovery (); ClsUtils. closeDiscoverableTimeout (mblustmthadapter); final effecthdevice implements thdevice = bondDevices. get (position); // The user-selected bluetooth device Bundle bun = new Bundle (); Constant. seteffecthdevice (effecthdevice); Intent intent = new Intent (mContenxt, ClientSendMsgAct. class); intent. putExtras (bun); startActivity (intent );}});

2) Start a thread to create a server. The two communication devices must use the same Bluetooth identifier, for example, Constant. PRIVATE_UUID.

@ Override public void run () {try {adapter = descrithadapter. getdefaadapter adapter (); serverSocket = adapter. listenUsingInsecureRfcommWithServiceRecord ("myBluetooth", Constant. PRIVATE_UUID); mHandler. obtainMessage (CREATE_SUCCESS ). sendToTarget (); while (status) {socket = serverSocket. accept (); doWork () ;}} catch (Exception e) {e. printStackTrace (); setActivityMsg (CREATE_FAIL, "an exception occurred when creating a service thread:" + e. getMessage ());}}

3. send text messages

1) before sending a text message, you must create a thread to use DataOutputStream to send the message.

Descrithdevice serverDevice; // The user-selected bluetooth device. For details, see section 2.1 (in the paired Bluetooth list, select the bluetooth device to be connected ).
Descrithsocket socket = serverDevice. createInsecureRfcommSocketToServiceRecord (Constant. PRIVATE_UUID );
DataOutputStream dataOutputStream = new DataOutputStream (socket. getOutputStream ());
String sendMessage = "nihao"; int f_len = sendMessage. getBytes ("UTF-8 "). length; // message length long totalLen = 4 + 1 + 1 + f_len; // The total length of data byte [] data = new byte [f_len]; data = sendMessage. getBytes ("UTF-8"); dataOutputStream. writeLong (totalLen); // 1. the total length of data written into dataOutputStream. writeByte (type); // 2. write type dataOutputStream. writeByte (f_len); // 3. the length of the message to be written to dataOutputStream. write (data); // 4. write message data dataOutputStream. flush ();

Currently, it is a test. Every time a message is sent, a thread is started and the message is not sent frequently, so it will not be affected.

 BluetoothClientThread bluetoothClientThread = new BluetoothClientThread(clientHandler,mContext,msg,socket); new Thread(bluetoothClientThread).start();

2) Receiving text messages was first created in the server thread.

Socket = serverSocket. accept (); dataInputStream = new DataInputStream (socket. getInputStream (); long totalLen = dataInputStream. readLong (); // The total length of byte type = dataInputStream. readByte (); // type byte len = dataInputStream. readByte (); // message Length byte [] ml = new byte [len]; int size = 0; int bytes Elen = 0; while (Bytes Elen <len) {size = dataInputStream. read (ml, 0, ml. length); cancelen + = size;} msg = new String (ml, "UTF-8"); setActivityMsg (MSG, msg); // callback the message to the activity, and refresh the received message.

3) Send image messages

You can send an image message in two steps. The name and size of the first image are the same as those of soket.

A) Name and size of the sent Image

Fins = new FileInputStream (Constant. FILE_PATH + imagePath); long fileDataLen = fins. available (); // The total object length int f_len = imagePath. getBytes ("UTF-8 "). length; // File Name length byte [] data = new byte [f_len]; data = imagePath. getBytes ("UTF-8"); long totalLen = 4 + 1 + 1 + f_len + fileDataLen; // The total length of data dataOutputStream = new DataOutputStream (socket. getOutputStream (); dataOutputStream. writeLong (totalLen); // 1. the total length of data written into dataOutputStream. writeByte (type); // 2. write type dataOutputStream. writeByte (f_len); // 3. write the length of the file name dataOutputStream. write (data); // 4. the data that is written to the file name dataOutputStream. flush ();

B) Formally send the image

FileInputStream fins = new FileInputStream ("actual image path"); while (size = fins. read (buffer, 0, 1024*10 ))! =-1) {dataOutputStream. write (buffer, 0, size); dataOutputStream. flush (); sendlen + = size; I ++; if (I % 10 = 0) {long time2 = Calendar. getInstance (). getTimeInMillis (); tspeed = sendlen/(time2-time1) * 1000/1024;} downbl = (sendlen * 100)/fileDataLen); Message msg = mHandler. obtainMessage (SEND_PROGRESS); Bundle bun = new Bundle (); bun. putFloat ("tspeed", downbl); msg. setData (bun); mHandler. sendMessage (msg); // update the sending progress}

4) receive image messages

Like sending and receiving, two steps are required. The first step is to receive the image name. The second step is to receive the image stream.

A) Name of the received Image

Byte len = dataInputStream. readByte (); // File Name Length byte [] fn = new byte [len]; dataInputStream. read (fn); // read the file name String filename = new String (fn, "UTF-8 ");

B) receive image streams

Byte [] buffer = new byte [1024*1024]; long datalength = totalLen-1-4-1-fn. length; // The file data long has Elen = 0; while (has Elen <datalength) {size = dataInputStream. read (buffer); fileOutputStream. write (buffer, 0, size); cancelen + = size; I ++; if (I % 10 = 0) {long time2 = Calendar. getInstance (). getTimeInMillis (); tspeed = receivelen/(time2-time1) * 1000/1024;} downbl = (receivelen * 100)/datalength ;}

 

After receiving text messages, the text message code is complete.

Download demo code: github

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.