Android Bluetooth Development

Source: Internet
Author: User

In view of the few Android Bluetooth development examples in China, and Bluetooth development is also rarely used, the materials found are not comprehensive.

Android supports Bluetooth development only from SDK 2.0, and simulators are not supported. Testing requires at least two mobile phones, which restricts the development of many technical personnel.

First, add permissions to androidmanifest. XML to perform Bluetooth operations.

<Uses-permissionandroid: Name = "android. Permission. effecth_admin"/>

<Uses-permissionandroid: Name = "android. Permission. Bluetooth"/>

Next, let's look at the API. All Android Bluetooth development classes are under the Android. Bluetooth package. For example, there are only eight classes.

 

We only need to use the following:

1. Bluetooth adapter, as its name implies, must be operated continuously until we establish a thsocket connection.

There are many methods in bluetoothadapter, which are commonly used as follows:

Canceldiscovery () is literally called to cancel the discovery, that is, when we are searching for a device, calling this method will not continue searching.

Disable () Disable Bluetooth

Enable, however, you will be prompted:

Intemtenabler = new intent (effecthadapter. action_request_enable );

Startactivityforresult (enabler, Recode); // same as startactivity (enabler );

Getaddress () Get the local Bluetooth address

Getdefaultadapter () obtains the default thadapter. In fact, only this method can be used to obtain the thadapter.

Getname () Get the local Bluetooth name

Getremotedevice (string address) obtains the remote Bluetooth device based on the Bluetooth address.

Getstate () gets the current status of the local Bluetooth adapter (it may be needed during debugging)

Isdiscovering () determines whether the device is currently being searched. True is returned.

Isenabled () determines whether the Bluetooth is enabled. If enabled, true is returned. Otherwise, false is returned.

Listenusingrfcommwithservicerecord (string name, UUID) based on the name, UUID is created and returns bluetoothserversocket, which is the first step to create the bluetoothsocket server.

Startdiscovery () to start searching. This is the first step of searching.

2. You can see the name of the thdevice. This class describes a bluetooth device.

Createrfcommsockettoservicerecord (uuiduuid) is created based on UUID and returns a effecthsocket

This method is also the purpose of getting ththdevice -- to create a thsocket

Other methods of this class, such as getaddress () and getname (), are the same as those of descrithadapter.

3. I believe everyone will be familiar with the Bluetooth removal of javasthserversocket. Since it is a socket, the methods should be similar,

This class has only three methods.

The difference between the two overloaded accept () and accept (inttimeout) is that later Methods specify the expiration time. Note that when you execute these two methods, the thread will be blocked until the client request is received (or after expiration) and should be run in the new thread!

Note that both methods return a thsocket, and the final connection is the connection between the server and the client.

Close () is not required. Translate -- close!

4. ipvthsocket, which is opposite to ipvthserversocket and is a client

A total of five methods will be used without accident

Close (), close

Connect () Connection

Getinptustream () gets the input stream

Getoutputstream () gets the output stream

Getremotedevice () gets the remote device. This indicates the remote Bluetooth device that is connected to the specified initthsocket.

Http://android.tgbus.com/Android/tutorial/201103/346657.shtml

Congratulations! You only need to use these four classes! But you may not understand it, because it is no different from watching the API, but it is translated... yes, most of the articles I have read are like this, so I still don't know how to get started (after all, my own level is limited). Next, let's take a look, let's take a look at my summary.

 

1. Obtain the local Bluetooth adapter

Descrithadapter
Madapter = descrithadapter. getdefaadapter adapter ();

2. Enable Bluetooth

If (! Madapter. isenabled ()){

// In the pop-up dialog box, the user is prompted to open

Intent enabler = new intent (effecthadapter. action_request_enable );

Startactivityforresult (enabler, request_enable );

// Force open without prompting

// Madapter. Enable ();

}

3. Search for devices
1) madapter. startdiscovery ()

This is the first step. You will find that no returned bluetooth device is found. How can you find it? Look down, don't worry

2) define broadcastreceiver. I will not talk much about broadcastreceiver. The Code is as follows:
Broadcastreceiver mreceiver = new broadcastreceiver (){
Public void onreceive (context, intent ){
String action = intent. getaction ();

// Find the device
If (descrithdevice. action_found.equals (Action )){
Descrithdevice device = intent

. Getparcelableextra (effecthdevice. extra_device );
If (device. getbondstate ()! = Effecthdevice. bond_bonded ){
Log. V (TAG, "Find device:" + device. getname ()

+ Device. getaddress ());
}
}
// Search complete
Else if (descrithadapter. action_discovery_finished

. Equals (Action )){
Settitle ("Search completed ");
If (mnewdevicesadapter. getcount () = 0 ){
Log. V (TAG, "Find over ");
}
}
// Execute the update list Code
}
};


In this way, when a new device is not found or the search is complete, the corresponding operations are executed in the two if items in the above Code, but the premise is that you must register

Broadcastreceiver. The Code is as follows:
Intentfilter filter = new intentfilter (effecthdevice. action_found );
Registerreceiver (mreceiver, filter );
Filter = new intentfilter (descrithadapter. action_discovery_finished );
Registerreceiver (mreceiver, filter );
(This code is generally written in oncreate ..)
3. Establish a connection. First, the Bluetooth connection supported by the android SDK (Version 2.0 and later) is established through the thinthsocket (if you are not correct, please refer to it), the server (thinthserversocket) and the client (thinthsocket) you must specify the same UUID to establish a connection. Because the method for establishing a connection will block the thread, the server and client should start a new thread connection.

1) server side:
// The UUID format is generally "XXXXXXXX-XXXX-xxxxxxxxxxxx ".

// Http://www.uuidgenerator.com
Application
Export thserversocket serversocket = madapter. listenusingrfcommwithservicerecord (serversocketname, UUID );
Serversocket. Accept ();
2) client:
// Do you still remember that we just obtained the thdevice in broadcastreceiver?
Export thsocket cliensocket = dcvice. createrfcommsockettoservicerecord (UUID );
Cliensocket. Connect ();
4. Data Transmission: Through the above operations, we have established a thsocket connection. data transmission is nothing more than a stream.
1) Get the stream
Inputstream = socket. getinputstream ();
Outputstream = socket. getoutputstream ();
2) write and read
This is the basic thing. I will not repeat it here.
I have finally finished writing this article. This is my learning experience over the past two days. I hope it will be helpful to friends who have Bluetooth needs! In addition, we mentioned

There are eight classes under Android. Bluetooth, and four other classes are not used. All the four classes are defined as constants, and I have never used them ..
Finally, I have attached several Bluetooth examples I have found to my end. I hope to engage in software development, especially Android development!

Http://www.eoeandroid.com/thread-18993-1-1.html

 

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.