(1) If you want to use the Bluetooth Android phone, you need to add Bluetooth access to the Androidmanifest file.
<uses-permission android:name= "Android.permission.BLUETOOTH"/> <uses-permission android:name= " Android.permission.BLUETOOTH_ADMIN "/>
Note: Permissions should be added to the Androidmanifest file <application> label outside of the,<manifest> tag
(2) to determine if there is a Bluetooth device that can be used, if there is to determine whether the Bluetooth device is turned on, if not open, then turn on Bluetooth
Bluetoothadapter mbluetoothadapter = Bluetoothadapter.getdefaultadapter (); if (mbluetoothadapter = = null) { Toast.maketext (Mainactivity.this, "This device does not support Bluetooth transmission! ", Toast.length_short). Show ();} Else{toast.maketext (Mainactivity.this, "This device supports Bluetooth transmission! ", Toast.length_short). Show (), if (!mbluetoothadapter.isenabled ()) { Intent enableintent = new Intent ( bluetoothadapter.action_request_enable); Enableintent.putextra (bluetoothadapter.extra_discoverable_duration); Startactivityforresult (Enableintent, REQUEST_ENABLE_BT); Toast.maketext (mainactivity.this, "Bluetooth device is turned on! ", Toast.length_short). Show ();
Note: 1) Bluetoothadapter on behalf of the local Bluetooth device, with Getdefaultadapter () to obtain the local Bluetooth device, the return value if NULL indicates that there is no Bluetooth device, otherwise it indicates that there is a Bluetooth device
2) Use the IsEnabled () method to determine whether the Bluetooth device is turned on, and if there is no open return value of false, you need to recall Startactivityforresult (Enableintent, REQUEST_ENABLE_BT); method to turn on the Bluetooth device. In the process of opening a Bluetooth device, a dialog box pops up asking for the rights of the Bluetooth communication,
(3) Find a Bluetooth device that has been paired with getbondeddevices (); method and put it in the collection, displayed in TextView
Set<bluetoothdevice> paireddevices=mbluetoothadapter.getbondeddevices (); if (paireddevices.size () > 0) {for (Bluetoothdevice bluetoothdevice:paireddevices) {Textview1.append (Bluetoothdevice.getname () + ":" + bluetoothdevice.getaddress () + "\ n");}}
Note: Each Bluetooth device that is already paired has a name and its MAC address.
You can look at my next article to search for a nearby Bluetooth device that is already open