Android Bluetooth Development In-depth analysis _android

Source: Internet
Author: User
Tags uuid

1. Response privileges using Bluetooth

Copy Code code as follows:

<uses-permission android:name= "Android.permission.BLUETOOTH"/>
<uses-permission android:name= "Android.permission.BLUETOOTH_ADMIN"/>

2. Configure the native Bluetooth module

Here first to understand the Bluetooth operation of a core class Bluetoothadapter

Copy Code code as follows:

Bluetoothadapter adapter = Bluetoothadapter.getdefaultadapter ();
Directly open the Bluetooth settings panel for the system
Intent Intent = new Intent (bluetoothadapter.action_request_enable);
Startactivityforresult (Intent, 0x1);
Open Bluetooth directly
Adapter.enable ();
Turn off Bluetooth
Adapter.disable ();
Turn on the Bluetooth Discovery feature on this computer (open 120 seconds by default, you can extend the time up to 300 seconds)
Intent discoveryintent = new Intent (bluetoothadapter.action_request_discoverable);
Discoverableintent.putextra (bluetoothadapter.extra_discoverable_duration, 300);/set duration (up to 300 seconds)

3. Search for Bluetooth devices

Use the Bluetoothadapter startdiscovery () method to search for Bluetooth devices

The StartDiscovery () method is an asynchronous method that is returned immediately after the call. This method searches for other Bluetooth devices, which lasts for 12 seconds. After the method is called, the search process is actually performed in a system service, so you can call the Canceldiscovery () method to stop the search (which can be invoked when the discovery request is not executed).

When the discovery is requested, the system starts searching for the Bluetooth device, during which the system sends the following three broadcasts:

Action_discovery_start: Start the search

Action_discovery_finished: End of search

Action_found: Find the device, this intent contains two EXTRA Fields:extra_device and Extra_class, including Bluetoodevice and Bluetoothclass respectively.

We can register the corresponding broadcastreceiver to receive the response broadcast in order to implement certain functions

Copy Code code as follows:

Create a broadcastreceiver that receives Action_found broadcasts
Private final Broadcastreceiver mreceiver = new Broadcastreceiver () {
public void OnReceive (context context, Intent Intent) {
String action = Intent.getaction ();
Discovery Device
if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {
Getting device objects from intent
Bluetoothdevice device = Intent.getparcelableextra (Bluetoothdevice.extra_device);
Put the device name and address in array adapter for display in ListView
Marrayadapter.add (Device.getname () + "\ n" + device.getaddress ());
}
}
};
Register Broadcastreceiver
Intentfilter filter = new Intentfilter (bluetoothdevice.action_found);
Registerreceiver (mreceiver, filter); Don't forget to unbind it later

4. Bluetooth Socket Communication

If you intend to recommend a connection between two Bluetooth devices, you must implement the server-side and client mechanism. When two devices have a connected bluetoothsocket under the same Rfcomm channel, the two devices can be said to have established a connection.

The way the server device acquires Bluetoothsocket with the client device is different. The server device is obtained by accepted a incoming connection, and the client device is obtained by opening a RFCOMM channel to the server.

Server-side implementation

By calling Bluetoothadapter's Listenusingrfcommwithservicerecord (String, UUID) method to obtain the Bluetoothserversocket (UUID is used for pairing between client and server side)

Call the Bluetoothserversocket accept () method to listen for connection requests and return a Bluetoothsocket instance (this method is the block method and should be placed in a new thread) if it is received.

If you do not want to accept another connection, call the Bluetoothserversocket Close () method to free the resource (after calling the method, the Bluetoothsocket instance that was previously obtained does not have close. However, since Rfcomm only allows one connection in one channel at a time, it is generally possible to close the bluetoothserversocket after a connection is accept.

Copy Code code as follows:

Private class Acceptthread extends Thread {
Private final Bluetoothserversocket Mmserversocket;

Public Acceptthread () {
Use a temporary object, the later assigned to Mmserversocket,
Because Mmserversocket is final
Bluetoothserversocket tmp = NULL;
try {
My_uuid is the app's ' s UUID string, also used by the client code
TMP = Mbluetoothadapter.listenusingrfcommwithservicerecord (NAME, My_uuid);
catch (IOException e) {}
Mmserversocket = tmp;
}

public void Run () {
Bluetoothsocket socket = NULL;
Keep listening until exception occurs or a socket is returned
while (true) {
try {
Socket = Mmserversocket.accept ();
catch (IOException e) {
Break
}
If a connection was accepted
if (socket!= null) {
Do work to manage the connection (in a separate thread)
Manageconnectedsocket (socket);
Mmserversocket.close ();
Break
}
}
}

/** 'll cancel the listening socket, and cause the thread to finish * *
public void Cancel () {
try {
Mmserversocket.close ();
catch (IOException e) {}
}
}


implementation of the client
Bluetoothservice on server side by search

Call the Bluetoothservice Listenusingrfcommwithservicerecord (String, UUID) method to get Bluetoothsocket (the UUID should be the same as the server-side UUID)

Call the Bluetoothsocket Connect () method (the method is the Block method), if the UUID matches the server-side UUID and the connection is accept by the server side, the Connect () method returns

Note: Before calling the Connect () method, you should make sure that no search device is currently available, or the connection will become very slow and prone to failure

Copy Code code as follows:

Private class Connectthread extends Thread {
Private final Bluetoothsocket Mmsocket;
Private final Bluetoothdevice Mmdevice;

Public Connectthread (Bluetoothdevice device) {
Use a temporary object, the later assigned to Mmsocket,
Because Mmsocket is final
Bluetoothsocket tmp = NULL;
Mmdevice = device;

Get a bluetoothsocket to connect with the given Bluetoothdevice
try {
My_uuid is the app's ' s UUID string, also used by the server code
TMP = Device.createrfcommsockettoservicerecord (MY_UUID);
catch (IOException e) {}
Mmsocket = tmp;
}

public void Run () {
Cancel discovery because it'll slow down the connection
Mbluetoothadapter.canceldiscovery ();

try {
Connect the device through the socket. This would block
Until it succeeds or throws an exception
Mmsocket.connect ();
catch (IOException connectexception) {
Unable to connect; Close the socket and get out
try {
Mmsocket.close ();
catch (IOException closeexception) {}
Return
}

Do work to manage the connection (in a separate thread)
Manageconnectedsocket (Mmsocket);
}

/** 'll cancel a in-progress connection, and close the socket * *
public void Cancel () {
try {
Mmsocket.close ();
catch (IOException e) {}
}
}


Connection management (data communication)
InputStream and OutputStream were obtained by the getInputStream () and Getoutputstream () methods of Bluetoothsocket respectively.

Read and write using the Read (bytes[]) and write (bytes[]) methods

Note: The read (bytes[] method blocks, knowing that information is read from the stream, and the write (bytes[]) method is not a regular block (for example, if another device is not in a timely read or the middle buffer is full, the Write method blocks)

Copy Code code as follows:

Private class Connectedthread extends Thread {
Private final Bluetoothsocket Mmsocket;
Private final InputStream Mminstream;
Private final OutputStream Mmoutstream;

Public Connectedthread (Bluetoothsocket socket) {
Mmsocket = socket;
InputStream tmpin = null;
OutputStream tmpout = null;

Get the input and output streams, using temp objects because
Member streams are final
try {
Tmpin = Socket.getinputstream ();
Tmpout = Socket.getoutputstream ();
catch (IOException e) {}

Mminstream = Tmpin;
Mmoutstream = Tmpout;
}

public void Run () {
byte[] buffer = new byte[1024]; Buffer store for the stream
int bytes; Bytes returned from read ()

Keep listening to the InputStream until a exception occurs
while (true) {
try {
Read from the InputStream
bytes = mminstream.read (buffer);
Send the obtained bytes The UI activity
Mhandler.obtainmessage (Message_read, Bytes,-1, buffer)
. Sendtotarget ();
catch (IOException e) {
Break
}
}
}

/* Call this ' from ' main activity ' to ' send data to the remote device * *
public void write (byte[] bytes) {
try {
Mmoutstream.write (bytes);
catch (IOException e) {}
}

/* Call this from the main activity to shutdown the connection * *
public void Cancel () {
try {
Mmsocket.close ();
catch (IOException e) {}
}
}


Reference material: Android official SDK, "Android/ophone Full development Handout"

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.