Android Bluetooth development

Source: Internet
Author: User
Tags uuid

This example is based on the Android demo

For the general software developers, Bluetooth is rarely used, especially Android Bluetooth development, domestic examples rarely Android for Bluetooth development from the 2.0 version of the SDK only started to support, and the simulator does not support, testing at least two phones, so restricting the development of a lot of technical personnel;
Since many developers now also have the need for Bluetooth development, but also for everyone to take a few detours, first of all I saved a little bit in the Android Bluetooth development experience to share with you!

First of all, to operate Bluetooth, first to add permissions in the Androidmanifest.xml

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

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


Then, take a look at api,android all of the Bluetooth development classes are under the Android.bluetooth package, such as only 8 classes


And we need to use only a few:

1.BluetoothAdapter

As the name implies, the Bluetooth adapter, until we establish bluetoothsocket connection, we have to constantly operate it bluetoothadapter in a lot of methods, commonly used are the following:

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

Disable () Turn off Bluetooth

Enable () Turn on Bluetooth, this method to turn on Bluetooth will not pop up the hint, 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);

GetAddress () get local Bluetooth address

Getdefaultadapter () Gets the default Bluetoothadapter, in fact, there is only one way to get Bluetoothadapter

GetName () Get the local Bluetooth name

Getremotedevice (String address) to obtain a remote Bluetooth device based on a Bluetooth location

GetState () Get the current status of the local Bluetooth adapter (it may feel more necessary when debugging)

Isdiscovering () to determine whether the device is currently being looked up, is true

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

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

StartDiscovery () Start search, this is the first step in searching

2.BluetoothDevice

Look at the name to know that this class describes a Bluetooth device

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

GetState () Bluetooth status here to say, only in the bluetoothadapter.state_on state can listen, specific can see Andrid API;

This approach is also the purpose of our acquisition of Bluetoothdevice-creating Bluetoothsocket
Other methods of this class, such as GetAddress (), GetName (), with Bluetoothadapter

3.BluetoothServerSocket

If you go except Bluetooth believe that everyone must be familiar with, since it is the socket, the method should be similar, this class only three methods two overloads of accept (), accept (inttimeout) The difference is that the following method specifies the obsolete time, It is important to note that the execution of these two methods, until the client's request (or after expiration), will block the thread, should be placed in a new thread to run!


It is also important to note that both methods return a bluetoothsocket, and the final connection is the server-side connection to the client's two Bluetoothsocket

Close () This goes without saying, translate--close!

4.BluetoothSocket

with Bluetoothserversocket, is the client altogether 5 methods, no accident, will use

Close (), close

Connect () connection

Getinptustream () get input stream

Getoutputstream () Get output stream

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

1. Get the local Bluetooth adapter

Bluetoothadapter
Madapter= Bluetoothadapter.getdefaultadapter ();

2. Turn on Bluetooth

if (!madapter.isenabled ()) {

Pop-up dialog prompts the user to be open after

Intent enabler = new Intent (bluetoothadapter.action_request_enable);

Startactivityforresult (enabler, request_enable);

Do not prompt, force open

Madapter.enable ();

}

3. Search Equipment
1) I just said it. Madapter.startdiscovery ()

Is the first step, you will find that there is no return Bluetooth device, how to know to find it? Look down, don't worry.

2) Definition broadcastreceiver, about broadcastreceiver not much to say, not today's discussion content, the code is as follows

[Java]View PlainCopy print?
  1. Broadcastreceiver mreceiver = new Broadcastreceiver () {
  2. public void OnReceive (context context, Intent Intent) {
  3. String action = Intent.getaction ();
  4. //Find device
  5. if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {
  6. Bluetoothdevice device = Intent
  7. . Getparcelableextra (Bluetoothdevice.extra_device);
  8. if (device.getbondstate ()! = bluetoothdevice.bond_bonded) {
  9. LOG.V (TAG, "Find device:" + device.getname ()
  10. + device.getaddress ());
  11. }
  12. }
  13. //Search Complete
  14. Else if (bluetoothadapter.action_discovery_finished
  15. . Equals (action)) {
  16. Settitle ("search completed");
  17. if (mnewdevicesadapter.getcount () = = 0) {
  18. LOG.V (TAG, "find over");
  19. }
  20. }
  21. }
  22. };

This way, if you do not find a new device or the search is complete, the corresponding operation is performed in the two if of the previous code, but only if you want to register first

Broadcastreceiver, the specific code is as follows

[Java]View PlainCopyprint?
    1. Intentfilter filter = new Intentfilter (Bluetoothdevice.action_found);
    2. Registerreceiver (mreceiver, filter);
    3. Filter = new Intentfilter (bluetoothadapter.action_discovery_finished);
    4. Registerreceiver (Mreceiver, filter) <span style="Font-family:simsun;" >;</span>


(This code is generally written in OnCreate ().) )
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


Bluetoothserversocket ServerSocket = Madapter. Listenusingrfcommwithservicerecord (SERVERSOCKETNAME,UUID);
Serversocket.accept ();


2) Client:
Remember when we just got bluetoothdevice in Broadcastreceiver?
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) Get the stream
InputStream = Socket.getinputstream ();
OutputStream = Socket.getoutputstream ();
2) write, read in
This is the basis of things, in which there is not much to repeat the
Finally finished, this is my two days of learning experience, hope to have Bluetooth needs of friends help! Besides, we mentioned before.

There are 8 classes under Android.bluetooth, there are 4 classes that are not used, and the 4 classes define constants, and I don't use them.

Finally, I found a few examples of Bluetooth attached to behind, hope to engage in software development, especially Android development friends after more communication, more sharing!

Add up to enable the device to be searched

Intent enabler = new Intent (bluetoothadapter.action_request_discoverable);

Startactivityforresult (enabler,request_discoverable);

Demo is to include the client and the server, respectively, placed on two mobile phones can communicate, we should be able to change the use of;

http://download.csdn.net/detail/q610098308/8681065
This is the official demo:
http://download.csdn.net/detail/q610098308/8628675

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.