Android Bluetooth Operation detailed

Source: Internet
Author: User

1. Enable Bluetooth and enable the device to be discoverable
1.1 Before you use an instance of the Bluetoothadapter class, you should enable the Isenable () method to check if the device has a Bluetooth adapter enabled. Use intent to prompt the user to enable Bluetooth and make the device discoverable Private voidStartbluetooth () {Bluetoothadapter BT = Bluetoothadapter. Getdefaultadapter(); Detect if Bluetooth is turned on if(!bt.isenabled ()) {Intent enableintent = NewIntent (Bluetoothadapter. action_request_enable);          Startactivityforresult (Enableintent, REQUEST_ENABLE_BT); }} 1.2 When returning intent activity, call Onactivityresult () to extract the master device name and MAC address protected voidOnactivityresult ( intRequestcode, intResultCode, Intent data) { if(Requestcode = = Request_enable_bt && ResultCode = = Activity. RESULT_OK) {Bluetoothadapter BT = Bluetoothadapter. Getdefaultadapter();              String address = bt.getaddress ();              String name = Bt.getname ();              String Toasttext = name + ":" + address; Toast. Maketext( This, Toasttext, Toast. Length_long). Show ();          Discoverable (); }1.3 request user authorization to allow the device to be discovered by other neighboring devices://Request user authorization to allow the device to be discoverable within 120 seconds Private voidDiscoverable () {Intent discoverableintent = NewIntent (Bluetoothadapter. action_request_discoverable);     StartActivity (discoverableintent); 2. Connect the Bluetooth enabled device   2.1For any Bluetooth app, you must add the following permissions in Androidmanifst.xml: <uses-permission android:name= "Android.permission.BLUETOOTH_ADMIN"/> <uses-permission android:name= "Android.permission.BLUETOOTH"/> 2.2 Creating socket connections to other Bluetooth devices we should continuously listen to the data in the socket stream within a thread. The connected stream can be written outside the thread. This connection is a blocking call, because the Bluetooth device discovery is a slow process that may reduce the connection rate.     Therefore, you need to cancel the device discovery before connecting to other devices. Blocked calls on a Bluetooth socket connection are returned only if the connection is successful or if the connection device has an exception. Once instantiated, the bluetoothconnection creates a connection to another device and starts listening for data from the connected device. Package Com.example.blueoothdemo;

Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.util.UUID;

Import Android.bluetooth.BluetoothAdapter;
Import Android.bluetooth.BluetoothDevice;
Import Android.bluetooth.BluetoothSocket;

/**
* Read and write Bluetooth devices
*
* @author Hbbliyong
*
*/
public class Bluetoothconnecion extends Thread {
Private final Bluetoothsocket Msocket;
Private final InputStream Minstream;
Private final OutputStream Moutstream;
byte[] buffer;
Private final Bluetoothadapter Madapter;
The UUID that is unique to this application,
private static final uuid My_uuid = UUID
. FromString ("Fa87c0d0-afac-11de-8a39-0800200c9a66");

Public bluetoothconnecion (Bluetoothdevice device) {
Bluetoothsocket tmp = NULL;
Madapter = Bluetoothadapter.getdefaultadapter ();
Get bluetoothsocket for specifying a bluetooth connection
try {
TMP = Device.createrfcommsockettoservicerecord (MY_UUID);
} catch (Exception e) {
E.printstacktrace ();
}
Msocket = tmp;

Establish a socket connection in a new thread to avoid FC
Thread connectionthread = new Thread (new Runnable () {
@Override
public void Run () {
TODO auto-generated Method Stub
Always cancel discovery because it reduces the speed of the connection
Madapter.canceldiscovery ();

Establish a connection to the Bluetoothsocket
try {
This is a blocking call that returns only when a successful connection or exception occurs
Msocket.connect ();
} catch (Exception e) {
E.printstacktrace ();
Device connection failed, closing socket
try {
Msocket.close ();
} catch (Exception E2) {
Todo:handle exception
E2.printstacktrace ();
}
}
}
});

Connectionthread.start ();

InputStream tmpin = null;
OutputStream tmpout = null;

Get bluetoothsoket input and output stream
try {
Tmpin = Msocket.getinputstream ();
Tmpout = Msocket.getoutputstream ();
Buffer = new byte[1024];
} catch (Exception e) {
E.printstacktrace ();
}
Minstream = Tmpin;
Moutstream = Tmpout;
}

public void Run () {
Keep Listening InputStream when connected
while (true) {
try {
Reading data from a socket stream
Minstream.read (buffer);
Send the retrieved data to the UI activity
} catch (Exception e) {
Todo:handle exception
The exception here marks the loss of the connection
Send the retrieved data to the UI activity
Break
}
}
}

public void write (byte[] buffer)
{
try {
Moutstream.write (buffer);
} catch (Exception e) {
E.printstacktrace ();
}
}

public void Cancel ()
{
try {
Msocket.close ();
} catch (Exception e) {
Todo:handle exception
E.printstacktrace ();
}
}
} 3. Listening and receiving Bluetooth connection requests        Before two Bluetooth devices interact, one of the communication devices must function as a server. It gets an Bluetoothserversocket instance and listens for inbound requests. This instance is obtained by invoking the Listenusingrfcommwithservicerecord () method on the Bluetooth adapter.   With this example, we can start listening for inbound requests from remote devices through the start () method. To make the primary device discoverable Intent discoverableintent = NewIntent (Bluetoothadapter. action_request_discoverable);  Startactivityforresult (Discoverableintent,discovery_request_bluetooth); Create a Bluetooth server and accept the connection protected voidOnactivityresult ( intRequestcode, intResultCode, Intent data) { if(Requestcode = = Discovery_request_bluetooth) { Booleanisdiscoverable = resultcode > 0; if(isdiscoverable) {//UUID//Uuid=uuid.fromstring ("a60f35f0-b93a-11de-8a39-08002009c666"); FinalUUID uuid = uuid. Randomuuid(); FinalString serverName = "Btserver"; FinalBluetoothadapter BT = Bluetoothadapter. Getdefaultadapter(); FinalBluetoothserversocket Bluetoothserver; Thread Listenthread = NewThread ( NewRunnable () {@Override Public voidRun () {// TODOauto-generated Method Stub Try{bluetoothserver = Bt.listenusingrfcommwithservicerecord (ServerName, UUID);                    Bluetoothsocket ServerSocket = bluetoothserver.accept ();                              Myhandleconnectionwiht (ServerSocket); } Catch(Exception e)                                                               {E.printstacktrace (); }                        } Private voidMyhandleconnectionwiht (Bluetoothsocket serversocket) {// TODOauto-generated method stub}});              Listenthread.start (); }          }     }

Android Bluetooth Operation detailed

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.