Android-bluetoothsocket set up socket __android for Bluetooth communication

Source: Internet
Author: User
We've all talked about it before. AndroidPlatform Bluetooth pairing, discovery, activation and other operations, this article began to pass Bluetoothsocketclass to establish a socket for Bluetooth communication. From Android 2.0Start supporting this feature, Bluetooth and LANLike through MACAddress to identify the remote device, establish the communication connection RFCOMMChannel to communicate in the input and output stream mode.

First, the connection equipment
Bluetooth communication is divided into ServerServer-side and ClientClients, which use the Bluetoothsocketclass to obtain the data in different ways.

1. As a server

If a device needs to be connected to two or more devices, it needs to be a ServerTo transmit, in Androidare provided in Bluetoothserversocketclass to handle the information sent by the user, and the server-side socket is accepting ( accepted) A client sent the BluetoothsocketRespond accordingly. The sample code is as follows:

Java code:
Private class Acceptthread extends Thread {

Private final Bluetoothserversocket Cwjserversocket;

Public Acceptthread () {

Bluetoothserversocket tmp = NULL; Use a temporary object instead, because Cwjserversocket is defined as final

try {

TMP = Myadapter.listenusingrfcommwithservicerecord (NAME, Cwj_uuid); Service Monitoring only

catch (IOException e) {}

Cwjserversocket = tmp;

}

public void Run () {

Bluetoothsocket socket = NULL;

while (true) {//Keep the connection until an exception occurs or the socket returns

try {

Socket = Cwjserversocket.accept (); If a connection agrees

catch (IOException e) {

Break

}

if (socket!= null) {

Manageconnectedsocket (socket); Manage an already connected Rfcomm channel on a separate thread.

Cwjserversocket.close ();

Break

}

}

}

public void Cancel () {//Cancel socket connection, and then the thread returns

try {

Cwjserversocket.close ();

catch (IOException e) {}

}

Copy the code here AndroidDevelopment network to remind you need to note that the server generally handle multiple tasks not tender blocking, must use asynchronous method here we open a thread, currently AndroidThe upper level of the virtual machine does not provide an I/O model, here we will explain the performance optimization solution under high load.

2. As a client

To initialize a connection to a remote device, you must first obtain the local Bluetoothdeviceobjects, the related methods in our AndroiD bluetooth APIOf BluetoothadapterIn the two articles of the class, there is no more detail here, and the relevant sample code is as follows:

Java code:

Private class Connectthread extends Thread {


Private final Bluetoothsocket Cwjsocket;


Private final Bluetoothdevice Cwjdevice;


Public Connectthread (Bluetoothdevice device) {


Bluetoothsocket tmp= null;

Cwjdevice= device;

try {


tmp= Device.createrfcommsockettoservicerecord (CWJ_UUID); Client-side Creation


catch (IOException e) {}

cwjsocket= tmp;


}


public void Run () {

Myadapter.canceldiscovery (); Cancel discovery of remote devices, which can degrade system performance

try {


Cwjsocket.connect ();


catch (IOException connectexception) {


try {


Cwjsocket.close ();

catch (IOException closeexception) {}


Return


}


Manageconnectedsocket (Cwjsocket); Manage an already connected Rfcomm channel on a separate thread

}

public void Cancel () {


try {

Cwjsocket.close ();

catch (IOException e) {}

}


}
Through the above introduction we can see theAndroidThe use of Bluetooth communication on the platform is relatively convenient and simple, the data on the specific communications we will be in the nextAndroidBluetoothAPIOfBluetoothsocket Class (2)Talked aboutManageconnectedsocketThe concrete realization.

Through the previous several explanations, many netizens believe that theAndroidBluetooth related development can be well mastered, throughBluetoothserversocketCan easily create a Bluetooth server, using theBluetoothsocketClass can handle the connection well, today we continue with the last content.AndroidHow to manage the connection of a Bluetooth socket, still use todayBluetoothsocketclass to handle the specific data stream.
InJavaThe process of data flow is simple and providesInputsream, Outputsreamand the conversion between the byte array. Todayeoeandroidwill be together with you to deal with the last legacyManageconnectedsocketThe details of the method, due to the possible interruption in Bluetooth transmission, so in order to prevent blocking need to open a worker thread, the relevant sample code

Java code:
Private class Connectedthread extends Thread {

Private final Bluetoothsocket Cwjsocket;

Private final InputStream Cwjinstream;

Private final OutputStream Cwjoutstream;

Public Connectedthread (Bluetoothsocket socket) {

Cwjsocket = socket;

InputStream tmpin = null; The definition above is final this is to use temp temporary object

OutputStream tmpout = null;

try {

Tmpin = Socket.getinputstream (); Using getInputStream as a stream processing

Tmpout = Socket.getoutputstream ();

catch (IOException e) {}

Cwjinstream = Tmpin;

Cwjoutstream = Tmpout;

}

public void Run () {

byte[] buffer = new byte[1024];

int bytes;

while (true) {

try {

bytes = cwjinstream.read (buffer);

Mhandler.obtainmessage (Message_read, Bytes,-1, buffer). Sendtotarget (); Passed to the UI thread

catch (IOException e) {

Break

}

}

}

public void write (byte[] bytes) {

try {

Cwjoutstream.write (bytes);

catch (IOException e) {}

}

public void Cancel () {

try {

Cwjsocket.close ();

catch (IOException e) {}

}

Copy Code
For specific connections, we see theAndroidThe platform uses theJavaStandard input and output stream operations,BluetoothsocketProvided bygetInputStream ()AndGetoutputstream ()Method can be very good to deal with our specific data.

Related Article

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.