Android Bluetooth technology bluetooth use process (detailed)

Source: Internet
Author: User
<span id="Label3"></p><strong><strong>one: the communication between Bluetooth devices mainly consists of four steps</strong></strong><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs ">设置蓝牙设备寻找局域网内可能或者匹配的设备连接设备设备之间的数据传输</code></pre></pre><strong><strong>two: specific Programming implementation</strong></strong><strong><strong>1. Activate the Bluetooth feature</strong></strong><p><p>The Bluetooth adapter bluetoothadapter is first obtained by calling the static method Getdefaultadapter (), and if the return is empty, the execution cannot continue. For example:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs cs">BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();<span class="hljs-keyword">if</span><span class="hljs-keyword">null</span>) { <span class="hljs-comment">// Device does not support Bluetooth</span>}</code></pre></pre><p><p>second, call IsEnabled () to query the status of the current Bluetooth device, if returned to false, it means that the Bluetooth device is not turned on, next you need to encapsulate a action_request_enable request to intent inside, Call the Startactivityforresult () method to enable the Bluetooth device, for example:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs cs"><span class="hljs-keyword">if</span> (!mBluetoothAdapter.isEnabled()) { <span class="hljs-keyword">new</span> Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);}</code></pre></pre><strong><strong>2. Find your device</strong></strong><p><p>Using the methods in the Bluetoothadapter class, you can look for remote devices (within about 10 meters) or other devices that have been matched (or bundled) on your phone. Of course it is necessary to make sure that the other Bluetooth device is turned on or the "enabled" feature is turned on (the other device can be found to be the prerequisite for you to initiate the connection). If the device can be found, it will feed back some of the other device information, such as name, mac address, etc., using this information, your device can choose to go to the other side to initialize a Connection.<br>If you are connected to the device for the first time, a paired request is automatically displayed to the User. When the device is paired, some of his basic information (primarily name and Mac) is saved and can be read using the Bluetooth api. Using a known Mac address, you can initiate a connection request to a remote Bluetooth device.<br>Match the difference between the device and the device on the connection: matching just means that the other device found your presence, and has a common identification code, and can be Connected. On connection: indicates that the current device shares a RFCOMM channel and that data can be exchanged between the Two. This means that the Bluetooth device must have been paired before establishing the Rfcomm channel.</p></p><strong><strong>3. Search for matching devices</strong></strong><p><p>Before establishing a connection, you must query the paired Bluetooth device set to pick a device for communication, such as you can query all paired Bluetooth devices and print them out using an array adapter:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs avrasm"><span class="hljs-keyword">Set</span><BluetoothDevice> pairedDevices =mBluetoothAdapter<span class="hljs-preprocessor">.getBondedDevices</span>()<span class="hljs-comment">;</span>// If there are paired devicesif (pairedDevices<span class="hljs-preprocessor">.size</span><span class="hljs-number">0</span>) { //Loop through paired devices for (BluetoothDevice device : pairedDevices) { <span class="hljs-keyword">Add</span><span class="hljs-keyword">and</span><span class="hljs-keyword">in</span> a ListView mArrayAdapter<span class="hljs-preprocessor">.add</span>(device<span class="hljs-preprocessor">.getName</span><span class="hljs-string">"\n"</span> + device<span class="hljs-preprocessor">.getAddress</span>())<span class="hljs-comment">;</span> }}</code></pre></pre><p><p>Setting up a Bluetooth connection requires only a MAC address that is Sufficient.</p></p><strong><strong>4. Scanning Equipment</strong></strong><p><p>Scan the device, only need to call the StartDiscovery () method, The process of this scan is approximately 12 seconds, the application for Action_found action needs to register a broadcastreceiver to accept the information that the device Scanned. For each device, the system broadcasts a action_found Action.</p></p><pre class="prettyprint"><code class=" hljs java"><span class="hljs-comment"><span class="hljs-comment">//use action_found to register the broadcast receiver for action</span></span><span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Final</span></span>Broadcastreceiver Mreceiver =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Broadcastreceiver () {<span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">OnReceive</span></span>(context context, Intent Intent) {String action = intent.getaction ();<span class="hljs-comment"><span class="hljs-comment">//discovery Equipment</span></span> <span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(BluetoothDevice.ACTION_FOUND.equals (ACTION)) {<span class="hljs-comment"><span class="hljs-comment">//get the Bluetooth device from the intent</span></span>Bluetoothdevice device = Intent.getparcelableextra (bluetoothdevice.extra_device);<span class="hljs-comment"><span class="hljs-comment">//add name and address to device adapter</span></span>Marrayadapter.add (device.getname () +<span class="hljs-string"><span class="hljs-string">"\ n"</span></span>+ device.getaddress ()); } }};<span class="hljs-comment"><span class="hljs-comment">//register a broadcast receiver</span></span>Intentfilter filter =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Intentfilter (bluetoothdevice.action_found); registerreceiver (mreceiver, filter);<span class="hljs-comment"><span class="hljs-comment">//remember to unregister the broadcast receiver when OnDestroy</span></span></code></pre><strong><strong>5. Enable to be found</strong></strong><p><p>If you want to make your device discoverable by other devices, wrap the action_request_discoverable action in Intent and call the Startactivityforresult (Intent, int) method. It will enable your device to be discovered without leaving your application out of the Picture. The Enable time by default is 120 seconds, and of course you can change the enable time by adding the Extra_discoverable_duration field (max. 300 Seconds) for Example:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs avrasm">Intent discoverableIntent = new Intent(BluetoothAdapter<span class="hljs-preprocessor">.ACTION</span>_REQUEST_DISCOVERABLE)<span class="hljs-comment">;</span>discoverableIntent<span class="hljs-preprocessor">.putExtra</span>(BluetoothAdapter<span class="hljs-preprocessor">.EXTRA</span><span class="hljs-number">300</span>)<span class="hljs-comment">;</span>startActivity(discoverableIntent)<span class="hljs-comment">;</span></code></pre></pre><p><p>After you run the code, a dialog box pops up prompting you to start the device so that it can be found (the system will turn it on if your Bluetooth function is not turned on), and if you are ready to discover a connection to the remote device, you do not need to turn on the device Discovery Feature. Because this feature is only needed when your application is on the server Side.</p></p><strong><strong>6. Connecting the device</strong></strong><p><p>In the application, to establish a connection between two Bluetooth devices, the client and Server-side code must be implemented (since any one device must be available as either a service side or a client). An open service to listen, an initiating connection request (using the Server-side Device's mac address). When they all have a Bluetooth socket on the same rfecomm channel, it can be thought that they are connected to each Other. The server side and the client are in different ways or their Bluetooth sockets. When a connection is heard, the server gets the Bluetooth socket. When the customer can open a Frcomm channel to the server side, the client obtains the Bluetooth socket.<br>Note: during this process, if two Bluetooth devices are not paired well, the Android system notifies the user via a notification or dialog box. Rfcomm connection requests are blocked before the user Chooses.</p></p><strong><strong>7. Connection to the server</strong></strong><p><p>When you want to connect two devices, one must serve as the server (by holding an open bluetoothserversocket), the purpose is to listen for incoming connection requests, when the supervisor hears to provide a connection on the bluetoothsocket to the client, When the client gets bluetoothsocket from bluetoothserversocket, it can destroy bluetoothserversocket, unless you want to listen for more connection Requests.<br>Basic steps for establishing a service socket and listening to a connection:<br>first, you get the Bluetoothserversocket object by calling the Listenusingrfcommwithservicerecord (string, UUID) method, and the parameter String represents the name of the Service. The UUID represents an identity that is connected to the client (a 128-bit format string id, equivalent to a pin), and the UUID must match before the connection can be Established.<br>Next call the Accept () method to listen for possible connection requests, and when heard, return a Bluetooth socket on the connection Bluetoothsocket.<br>finally, after you hear a connection, you need to call the close () method to close the Listener. (general Bluetooth device is a point-to-point transmission)<br>Note: the Accept () method should not be placed inside the main acitvity because it is a blocking call (the program stops there until the connection request is heard). The workaround is to create a new thread to Manage. For example:</p></p><strong><strong>8. Connection of the client</strong></strong><p><p>In order to initialize a connection to a remote device, you first need to obtain a Bluetoothdevice object that represents the Device. To get Bluetoothsocket and initialize the connection through the Bluetoothdevice object, proceed as Follows:<br>Use the method Createrfcommsockettoservicerecord (UUID) in the Bluetoothdevice object to get Bluetoothsocket. The UUID is the matching Code. then, Call the Connect () method to. If the remote device receives the connection, they will share the Rffcomm channel during the communication, and connect returns.<br>Note: the Conncet () method is also a blocking call, which is typically established in a separate thread to invoke the Method. Connecting to connect () should not be initiated during device discover, which slows down significantly so that the connection Fails. And the data transfer is done only by calling the close () method to close the connection, which saves the System's internal Resources.</p></p><strong><strong>9. Managing Connections</strong></strong><p><p>When the device is connected, each device has its own bluetoothsocket. Can realize the sharing of data between Devices.<br>The input and output streams are obtained first by calling the getInputStream () and Getoutputstream () methods.<br>The data is then read or written by calling read (byte[]) and write (byte[]).<br>Implementation Details: for read and write operations are blocking calls, you need to establish a dedicated thread to Manage.</p></p><strong><strong>10. Permission Settings</strong></strong><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs applescript"><uses-permissionandroid:<span class="hljs-property">name</span>=<span class="hljs-string">"android.permission.BLUETOOTH_ADMIN"</span> /><uses-permissionandroid:<span class="hljs-property">name</span>=<span class="hljs-string">"android.permission.BLUETOOTH"</span> /></code></pre></pre> <p><p>Android Bluetooth technology bluetooth use process (detailed)</p></p></span>

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.