Android Bluetooth development

Source: Internet
Author: User

First, configure permissions

Androidmanifest.xml Add Permissions

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

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

Second, the relevant API

Android All of the classes on Bluetooth development are under the Android.bluetooth package:

1.BluetoothAdapter class :

Describe:

Bluetooth adapter, which represents the local Bluetooth adapter device. The Bluetoothadapter class allows users to perform basic Bluetooth tasks. For example: Initialize a device's search, query a matching set of devices, initialize a Bluetoothdevice class with a known MAC address, create a Bluetoothserversocket class to listen for other devices to the local connection request, and so on.

To get this bluetoothadapter class that represents the local Bluetooth adapter, call Getdefaultadapter () as a static method. This is the first step to use for all Bluetooth actions. When the local adapter is available, the user can obtain a series of Bluetoothdevice objects representing all the matched devices that have the Getbondeddevice () method, and the StartDiscovery () method to start the device search or create a Bluetoothserversocket class that listens for new connection requests through the Listenusingrfcommwithservicerecord (String, UUID) method.

Method:

1)canceldiscovery ()

By literal means, is to cancel the discovery, that is, when we are searching the device, call this method will not continue to search

2) Disable () turn off Bluetooth

3) enable () turn on Bluetooth

This method to turn on Bluetooth will not pop up the prompt, more time we need to ask the user whether to open, the two lines of code is also open Bluetooth, but will prompt the user:

Intemtenabler=new Intent (bluetoothadapter.action_request_enable);

Startactivityforresult (Enabler,recode);// with startactivity (enabler);

4) getaddress () get local Bluetooth address

5) Getdefaultadapter () Get the default bluetoothadapter, in fact, there's only one way to get Bluetoothadapter

6) GetName () get local bluetooth name

7) Getremotedevice (String address) get a remote Bluetooth device based on the Bluetooth address

8) getState () Get the current status of the local Bluetooth adapter (more needed when it feels possible to debug)

9) isdiscovering () to determine whether a device is currently being located, returns True

ten) isenabled () Determines whether Bluetooth is turned on, turned on returns True, otherwise, returns false

One ) Listenusingrfcommwithservicerecord (String name,uuid UUID) by name, the UUID creates and returns Bluetoothserversocket, which is the first step in creating the Bluetoothsocket server side

startdiscovery () Start the search, this is the first step in the search

2.bluetoothdevice class

Describe

Represents a remote Bluetooth device. Lets you create a bluetoothdevice with your own device or query for information such as name, address, class, and connection status.

For Bluetooth hardware addresses, this class is just a thin wrapper. The object of this class is immutable. Operations on this class are performed on the remote Bluetooth hardware using the Bluetoothadapter class that is used to create the Bluetoothdevice class.

To get Bluetoothdevice, class, use the Bluetoothadapter.getremotedevice (String) method to create a representation A device that is known to have a MAC address (the user can do a lookup to the device with the Bluetoothadapter Class) or a linked device collection that gets the return value through Bluetoothadapter.getbondeddevices () to get the device.

Method

1) Createrfcommsockettoservicerecord (uuiduuid) creates and returns a bluetoothsocket based on the UUID

This approach is also the purpose of our acquisition of Bluetoothdevice-creating Bluetoothsocket

2) getaddress () with Bluetoothadapter

3) GetName () with Bluetoothadapter

3.Bluetoothserversocket

Describe

A Bluetooth listening port. The Bluetooth port listener interface is similar to the TCP port: Socket and ServerSocket classes. On the server side, use the Bluetoothserversocket class to create a listening service port. When a connection is accepted by Bluetoothserversocket, it returns a new bluetoothsocket to manage the connection. On the client side, use a separate Bluetoothsocket class to initialize an external connection and manage the connection.

The most commonly used Bluetooth port is Rfcomm, which is the type supported by the Android API. Rfcomm is a connection-oriented, data stream transmission via a Bluetooth module, which is also known as the serial port specification (Serial Port PROFILE,SPP).

In order to create a new connection ready to listen to the BluetoothServerSocket class, the use of the BluetoothAdapter.listenUsingRfcommWithServiceRecord() method. The accept() method is then called to listen for the link's request. The call is blocked until the connection is established, that is, it returns a BluetoothSocket class to manage the connection. After each acquisition of the class, it is best to call the method under the class if you no longer need to accept the connection BluetoothServerSocket close() . Closing the BluetoothServerSocket class does not close the already returned BluetoothSocket class.

BluetoothSocketClass thread safety. In particular, the close() method will always give up outside operations and shut down the server port.

Method

1)accept ()

Block until a connection has been established. (Translator Note: The default time-out is set to-1, see source code)

Returns a connected Bluetoothsocket class on a successfully established connection.

Whenever the call returns, it can be called to receive a new connection later.

2) Accept (inttimeout)

The connection is blocked until the timeout period is established.

Returns a connected Bluetoothsocket class on a successfully established connection.

Whenever the call returns, it can be called to receive a new connection later.

3)Close ()

Used to discard calls from another thread.

Close the port immediately and release all related resources.

Causes blocking in that port on other threads, causing the system to throw an IO exception immediately.

Closing Bluetoothserversocket does not turn off any bluetoothsocket that accept self-acceptance ().

4.BluetoothSocket

Describe

Connected or connected to a Bluetooth socket (socket).

The Bluetooth port listener interface is similar to the TCP port: Socket and ServerSocket classes. On the server side, use the Bluetoothserversocket class to create a listening service port. When a connection is accepted by Bluetoothserversocket, it returns a new bluetoothsocket to manage the connection. On the client side, use a separate Bluetoothsocket class to initialize an external connection and manage the connection.

The most commonly used Bluetooth port is Rfcomm, which is the type supported by the Android API. Rfcomm is a connection-oriented, data stream transmission via a Bluetooth module, which is also known as the serial port specification (Serial Port PROFILE,SPP).

In order to create a bluetoothsocket to connect to a known device, use Method Bluetoothdevice.createrfcommsockettoservicerecord (). Then call the Connect () method to try a connection for the remote device. This call will be blocked to instruct a connection to be established or the link to fail.

To create a bluetoothsocket as a server (or "host"), view the Bluetoothserversocket documentation.

Each time the port is connected successfully, whether it is initialized to the client or accepted as the server side, the IO stream is opened via getInputStream () and Getoutputstream () to obtain the respective InputStream and OutputStream objects

Bluetoothsocket class thread safety. In particular, the close () method will always abandon external operations and shut down the server port immediately.

Method

1) Close () Close

2) Connect () Connection

3) Getinptustream () Get input stream

4) Getoutputstream () get output stream

5) Getremotedevice () Gets the remote device, which refers to the remote Bluetooth device that gets the bluetoothsocket specified connection.

Third, the operation

1 , get the local Bluetooth adapter      

Bluetoothadapter madapter= Bluetoothadapter.getdefaultadapter ();

2 , turn on Bluetooth

if (! madapter.isenabled ()) {// Popup dialog box prompts the user to open  new  Intent (bluetoothadapter.action_request_enable) ; Startactivityforresult (enabler, request_enable); // Do not prompt, force open // madapter.enable (); }

3. Search Equipment

Broadcastreceiver Mreceiver =NewBroadcastreceiver () { Public voidOnReceive (Context context, Intent Intent) {String action=intent.getaction (); //Find Device      if(BluetoothDevice.ACTION_FOUND.equals (ACTION)) {Bluetoothdevice device=Intent.getparcelableextra (Bluetoothdevice.extra_device); if(Device.getbondstate ()! =bluetoothdevice.bond_bonded) {LOG.V (TAG,"Find device:" +Device.getname ()+device.getaddress ()); }}//Search Complete      Else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals (ACTION)) {Settitle ("Search Complete"); if(Mnewdevicesadapter.getcount () = = 0) {log.v (TAG,"Find Over"); }}//code to execute the update list}};

Code in OnCreate ()

Newnew  intentfilter (bluetoothadapter.action_discovery_finished); Registerreceiver ( Mreceiver, filter);

4. Establish the connection

First Android The Bluetooth connection supported by the SDK (2.0 or more) is established via Bluetoothsocket (incorrect), the server side (Bluetoothserversocket) and the client (bluetoothsocket) need to specify the same UUID in order to establish the connection because The method of establishing a connection blocks the thread, so both the server side and the client should start a new thread connection

1 ) server-side:

// The UUID format is generally "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" to         // http://www.uuidgenerator.com Application  = madapter. Listenusingrfcommwithservicerecord (Serversocketname,uuid); serversocket.accept ();

2) Client:

Bluetoothsocket cliensocket=dcvice. Createrfcommsockettoservicerecord (UUID); Cliensocket.connect ();

5 , data transmission, through the above operation, has been established bluetoothsocket connected, data transmission is nothing more than the form of flow

1 ) Gets the stream

InputStream == Socket.getoutputstream ();

2 ) Write, read in

Android Bluetooth development

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.