Find and connect Android Bluetooth devices

Source: Internet
Author: User

1. Permissions
Using a Bluetooth device requires opening permissions in manifest, which is located below.

[HTML]View Plaincopy
  1. <manifest ... >
  2. <application ... >
  3. ...
  4. </Application>
  5. Permission to use a Bluetooth device
  6. <uses-permission android:name="Android.permission.BLUETOOTH" />
  7. Manage permissions for a Bluetooth device
  8. <uses-permission android:name="Android.permission.BLUETOOTH_ADMIN" />
  9. </manifest>


2. Turn on Bluetooth
Get the Bluetooth adapter (android.bluetooth.BluetoothAdapter), check if the device supports Bluetooth, and turn on Bluetooth if it is supported.

[Java]View Plaincopy
  1. Check if the device supports Bluetooth
  2. adapter = Bluetoothadapter.getdefaultadapter ();
  3. if (adapter = = null)
  4. {
  5. //device does not support Bluetooth
  6. }
  7. Turn on bluetooth
  8. if (!adapter.isenabled ())
  9. {
  10. Intent Intent = new Intent (bluetoothadapter.action_request_enable);
  11. //Set Bluetooth visibility for up to 300 seconds
  12. Intent.putextra (Bluetoothadapter.extra_discoverable_duration, 300);
  13. Context.startactivity (Intent);
  14. }


3. Get a paired Bluetooth device (Android.bluetooth.BluetoothDevice)
The first time you connect a Bluetooth device you need to pair, once the pairing is successful, the information of the device will be saved, later connected to no longer need to pair, so the paired device is not necessarily able to connect.

[Java]View Plaincopy
    1. Bluetoothadapter adapter = Bluetoothadapter.getdefaultadapter ();
    2. set<bluetoothdevice> devices = Adapter.getbondeddevices ();
    3. for (int i=0; I<devices.size (); i++)
    4. {
    5. Bluetoothdevice device = (bluetoothdevice) devices.iterator (). Next ();
    6. System.out.println (Device.getname ());
    7. }


4. Search for nearby Bluetooth devices
After the adapter searches for a Bluetooth device, the results are broadcast out, so you need to customize a class that inherits the broadcast and obtain and process the search results for the Bluetooth device in the OnReceive method.

[Java]View Plaincopy
    1. Set up broadcast information filtering
    2. Intentfilter intentfilter = new Intentfilter ();
    3. Intentfilter.addaction (Bluetoothdevice.action_found);
    4. Intentfilter.addaction (bluetoothdevice.action_bond_state_changed);
    5. Intentfilter.addaction (bluetoothadapter.action_scan_mode_changed);
    6. Intentfilter.addaction (bluetoothadapter.action_state_changed);
    7. Register a broadcast receiver to receive and process search results
    8. Context.registerreceiver (receiver, intentfilter);
    9. Looking for a Bluetooth device, Android will send the found device in broadcast form
    10. Adapter.startdiscovery ();


Custom Broadcast Classes

[Java]View Plaincopy
  1. Private Broadcastreceiver receiver = new Broadcastreceiver () {
  2. @Override
  3. public void OnReceive (context context, Intent Intent) {
  4. String action = Intent.getaction ();
  5. if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {
  6. Bluetoothdevice device = Intent.getparcelableextra (Bluetoothdevice.extra_device);
  7. System.out.println (Device.getname ());
  8. }
  9. }
  10. }


5. Pairing and status monitoring of Bluetooth devices

[Java]View Plaincopy
  1. Private Broadcastreceiver receiver = new Broadcastreceiver () {
  2. @Override
  3. public void OnReceive (context context, Intent Intent) {
  4. String action = Intent.getaction ();
  5. if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {
  6. //Get the Bluetooth device found
  7. Bluetoothdevice device = Intent.getparcelableextra (Bluetoothdevice.extra_device);
  8. System.out.println (Device.getname ());
  9. //If the found device meets the device to be connected, process
  10. if (Device.getname (). Equalsignorecase (name)) {
  11. //The process of searching for Bluetooth devices consumes a lot of resources, and once you find a device that needs to be connected, you need to close the search promptly
  12. Adapter.canceldiscovery ();
  13. //Get the Bluetooth device connection status
  14. Connectstate = Device.getbondstate ();
  15. switch (connectstate) {
  16. //Not paired
  17. Case Bluetoothdevice.bond_none:
  18. //Pairing
  19. try {
  20. Method Createbondmethod = Bluetoothdevice.  Class.getmethod ("Createbond");
  21. Createbondmethod.invoke (device);
  22. } catch (Exception e) {
  23. E.printstacktrace ();
  24. }
  25. Break ;
  26. //Paired
  27. Case bluetoothdevice.bond_bonded:
  28. try {
  29. //Connection
  30. Connect (device);
  31. } catch (IOException e) {
  32. E.printstacktrace ();
  33. }
  34. Break ;
  35. }
  36. }
  37. } Else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals (ACTION)) {
  38. //state-changed broadcast
  39. Bluetoothdevice device = Intent.getparcelableextra (Bluetoothdevice.extra_device);
  40. if (Device.getname (). Equalsignorecase (name)) {
  41. Connectstate = Device.getbondstate ();
  42. switch (connectstate) {
  43. Case Bluetoothdevice.bond_none:
  44. Break ;
  45. Case bluetoothdevice.bond_bonding:
  46. Break ;
  47. Case bluetoothdevice.bond_bonded:
  48. try {
  49. //Connection
  50. Connect (device);
  51. } catch (IOException e) {
  52. E.printstacktrace ();
  53. }
  54. Break ;
  55. }
  56. }
  57. }
  58. }
  59. }


6. Connection of Bluetooth devices

[Java]View Plaincopy
      1. Private void Connect (Bluetoothdevice device) throws IOException {
      2. //fixed UUID
      3. final String spp_uuid = "00001101-0000-1000-8000-00805F9B34FB";
      4. UUID uuid = uuid.fromstring (spp_uuid);
      5. Bluetoothsocket socket = Device.createrfcommsockettoservicerecord (UUID);
      6. Socket.connect ();
      7. }

Find and connect Android Bluetooth devices

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.