Android Bluetooth operation details, android Bluetooth details

Source: Internet
Author: User

Android Bluetooth operation details, android Bluetooth details
1. Enable Bluetooth and make the device discoverable
1.1 enable the isEnable () method to check whether the device has enabled the Bluetooth adapter before using an instance of the descrithadapter class. // Use the intent to prompt the user to enable Bluetooth and make the device discoverablePrivate VoidStartBluetooth () {descrithadapter bt = descrithadapter.Getdefaadapter Adapter(); // Checks whether Bluetooth is enabledIf(! Bt. isEnabled () {Intent enableIntent =NewIntent (effecthadapter.ACTION_REQUEST_ENABLE); StartActivityForResult (enableIntent, REQUEST_ENABLE_BT);} 1.2 When an intent activity is returned, onActivityResult () is called to extract the master device name and mac addressProtected VoidOnActivityResult (IntRequestCode,IntResultCode, Intent data ){If(RequestCode = REQUEST_ENABLE_BT & resultCode = Activity.RESULT_ OK) {Descrithadapter bt = descrithadapter.Getdefaadapter Adapter(); 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 so that the device can be found by other nearby devices: // request user authorization to make the device discoverable within 120 secondsPrivate VoidDiscoverable () {Intent discoverableIntent =NewIntent (effecthadapter.ACTION_REQUEST_DISCOVERABLE); StartActivity (discoverableIntent);} 2. Enable bluetooth device connection 2.1For any Bluetooth Application, you must add the following permissions to AndroidManifst. xml: <uses-permission android: name ="Android. permission. effecth_admin"/> <Uses-permission android: name ="Android. permission. BLUETOOTH"/> 2.2 When a socket connection is created to another bluetooth device, we should continuously listen to data in the socket stream within one thread. The connection stream can be written outside the thread. This kind of connection is a blocking call. Because Bluetooth devices find it a slow process, the connection rate may be reduced. Therefore, you must cancel device discovery before connecting to other devices. The call is blocked when a Bluetooth socket is connected. It is returned only when the connection is successful or the device is connected to an exception. Once instantiated, thconnection creates a connection to another device and starts to listen to data from the connected device. Package com. example. blueoothdemo;

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

Import android. bluetooth. javasthadapter;
Import android. bluetooth. systthdevice;
Import android. bluetooth. javasthsocket;

/**
* Reading and writing Bluetooth devices
*
* @ Author hbbliyong
*
*/
Public class extends thconnecion extends Thread {
Private final ipvthsocket mSocket;
Private final InputStream mInStream;
Private final OutputStream mOutStream;
Byte [] buffer;
Private final initialize thadapter mAdapter;
// The unique UUID of the application,
Private static final UUID MY_UUID = UUID
. FromString ("fa87c0d0-afac-11de-8a39-0800200c9a66 ");

Public incluthconnecion (incluthdevice device ){
Optional thsocket tmp = null;
MAdapter = descrithadapter. getdefaadapter adapter ();
// Obtain the thsocket used for the specified Bluetooth connection
Try {
Tmp = device. createRfcommSocketToServiceRecord (MY_UUID );
} Catch (Exception e ){
E. printStackTrace ();
}
MSocket = tmp;

// Establish a socket connection in the new thread to avoid FC
Thread connectionThread = new Thread (new Runnable (){
@ Override
Public void run (){
// TODO Auto-generated method stub
// Always cancel the discovery because it will reduce the connection speed
MAdapter. cancelDiscovery ();

// Establish a connection to the thsocket
Try {
// This is a blocking call. It is returned only when a successful connection or an exception occurs.
MSocket. connect ();
} Catch (Exception e ){
E. printStackTrace ();
// Device connection failed. Disable socket
Try {
MSocket. close ();
} Catch (Exception e2 ){
// TODO: handle exception
E2.printStackTrace ();
}
}
}
});

ConnectionThread. start ();

InputStream tmpIn = null;
OutputStream tmpOut = null;

// Obtain the input and output streams of BluetoothSoket.
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 for InputStream during connection
While (true ){
Try {
// Read data from the socket stream
MInStream. read (buffer );
// Send the obtained data to the UI Activity
} Catch (Exception e ){
// TODO: handle exception
// The exception indicates the loss of the connection.
// Send the obtained 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. listen to and receive Bluetooth connection requests Before two bluetooth devices interact, one communication device must act as a server. It obtains a thserversocket instance and listens to inbound requests. This instance is obtained by calling the listenUsingRfcommWithServiceRecord () method on the Bluetooth adapter. With this instance, we can use the start () method to start listening for inbound requests from remote devices. // Make the master device in the discoverable status Intent disCoverableIntent =NewIntent (effecthadapter.ACTION_REQUEST_DISCOVERABLE); StartActivityForResult (disCoverableIntent, DISCOVERY_REQUEST_BLUETOOTH); // create a Bluetooth server and accept the connectionProtected 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 ";FinalDescrithadapter bt = descrithadapter.Getdefaadapter Adapter();FinalEffecthserversocket implements thserver; Thread listenThread =NewThread (NewRunnable () {@ OverridePublic VoidRun (){//TODOAuto-generated method stubTry{Export thserver = bt. listenUsingRfcommWithServiceRecord (serverName, uuid); export thsocket serverSocket = export thserver. accept (); myHandleConnectionWiht (serverSocket );}Catch(Exception e) {e. printStackTrace ();}}Private VoidMyHandleConnectionWiht (javasthsocket serverSocket ){//TODOAuto-generated method stub }}); listenThread. start ();}}}

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.