Android Bluetooth Development Case Analysis _android

Source: Internet
Author: User
Tags socket uuid

When using the mobile phone, Bluetooth communication brings us a lot of convenience. So how does Bluetooth develop on Android phones? This article illustrates the knowledge of Android Bluetooth development in a practical way.

1, the use of Bluetooth response authority

xml/html Code

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

2, configure the native Bluetooth module

Here first to understand the Bluetooth operation of a core class bluetoothadapter.

Bluetoothadapter adapter = Bluetoothadapter.getdefaultadapter ();  
  
Directly open the System Bluetooth Settings panel  
  
Intent Intent = new Intent (bluetoothadapter.action_request_enable);  
  
Startactivityforresult (Intent, 0x1);  
  
Open Bluetooth  
  
adapter.enable directly ();  
  
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);  
  

3, search Bluetooth equipment

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.

Create a Broadcastreceiver private final broadcastreceiver that receives the Action_found broadcast  
  
mreceiver = new Broadcastreceiver () { Public  
  
 void OnReceive (context context, Intent Intent) {  
  
  String action = intent.getaction ();  
  
  Discovery Device  
  
  if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {  
  
   //Get device object from intent  
  
   bluetoothdevice device = Intent.getparcelableextra (bluetoothdevice.extra_device);  
  
   Place the device name and address into array adapter to display  
  
   Marrayadapter.add (device.getname () + "\ n" + device.getaddress ()) in ListView;  
 }  
};  
  
Registered Broadcastreceiver  
  
intentfilter filter = new Intentfilter (bluetoothdevice.action_found);  
  

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 the client and the server side).

Calls the Bluetoothserversocket accept () method to listen for a connection request and, if so, returns a Bluetoothsocket instance (this method is the block method and should be placed in a new thread).

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.

Private class Acceptthread extends Thread {private final bluetoothserversocket mmserversocket; Public Acceptthread () {//Use a temporary object and is later assigned to Mmserversocket,//Because Mmser  
  
  Versocket is final bluetoothserversocket tmp = NULL; try {//My_uuid is the app ' s UUID string, also used by the client code TMP = MBLUETOOTHADAPTER.LISTENUSINGRF  
  Commwithservicerecord (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 = Mmservers  
   Ocket.accept ();  
   catch (IOException e) {break; }//If a connection was accepted if (socket!= null) {//Does work to manage the connection (in a Separ  
    Ate thread) manageconnectedsocket (socket);  
    Mmserversocket.close ();  
   Break  
 } }/** 'll cancel the listening socket, and cause the thread to finish */public void Cancel () {try {  
  Mmserversocket.close ();  The catch (IOException e) {}}}

implementation of the client

The server-side bluetoothservice are searched by search.

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

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

Note: Before calling the Connect () method, you should make sure that no search device is currently available, otherwise the connection becomes very slow and easy to fail.

Private class Connectthread extends Thread {private final bluetoothsocket mmsocket;  
  
  
  
 Private final Bluetoothdevice Mmdevice;  
  
  Public Connectthread (Bluetoothdevice device) {//Use a temporary object this is 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 UUID strin  
  G, 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.c  
  Anceldiscovery (); try {//Connect the device through the socket.  
  This would block//until it succeeds or throws a 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 an in-progress connection, and close the socket */public void Cancel () {try {Mmsoc  
  
  Ket.close ();  The catch (IOException e) {}}}

5. Connection management (data communication)

InputStream and OutputStream were obtained through the Bluetoothsocket getInputStream () and Getoutputstream () methods respectively.

Use the Read (bytes[]) and write (bytes[]) methods to read and write separately.

Note: The read (bytes[] method blocks, knowing that the 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).

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 {TM  
  
   PIn = Socket.getinputstream ();  
  
  Tmpout = Socket.getoutputstream ();  
  
  The 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 (tr  
  
UE) {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 the ' main activity ' to ' send data to the remote device */public void  
  
  Write (byte[] bytes) {try {mmoutstream.write (bytes); The catch (IOException e) {}}/* Call the ' main activity ' to shutdown the connection/PU  
  
  blic void Cancel () {try {mmsocket.close ();   The catch (IOException e) {}}}

  above on the development of Android Bluetooth simple sample code, follow-up to continue to collate relevant information, thank you for your support for this site!

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.