Android development-Bluetooth operation

Source: Internet
Author: User

First, because there is no Bluetooth device on the simulator, we need an Android system containing a bluetooth device. Second, to operate the bluetooth device on the device, we need to declare two permissions in AndroidManifest: <uses-permission android: name = "android. permission. export th_admin "/> <uses-permission android: name =" android. permission. BLUETOOTH "/> the first permission is called" BLUETOOTH Management ", which is the setting of BLUETOOTH visibility, scanning device, the second permission set for disabling and other operations is the normal "Bluetooth operation permission". You can enable Bluetooth and search for matching devices. This class is mainly used to operate the basic services of Bluetooth. For example, initialize the visibility of a device, query the device set that can match, and use a known MAC address to initialize a bluetooth device class ), create a descrithserversocket class to listen for connection requests from other devices to the local machine. Which is a remote Bluetooth device. You can create a thdevice with its own device or query the device information, such as the name, address, class, and connection status. To configure the local Bluetooth module, you must first understand the core category of Bluetooth operations. getdefaadapter adapter (); 02 // directly open the system's bluetooth settings panel 03 Intent intent = new Intent (effecthadapter. ACTION_REQUEST_ENABLE); 04 startActivityForResult (intent, 0x1); 05 // enable Bluetooth 06adapter directly. enable (); 07 // disable Bluetooth 08adapter. disable (); 09 // enable the Bluetooth detection function of the Local Machine (120 seconds by default, up to 300 seconds can be extended) 10discoverableIntent. putExtra (effecthadapter. EXTRA_DISCOVE RABLE_DURATION, 300); // set the duration (up to 300 seconds) Intent discoveryIntent = new Intent (effecthadapter. ACTION_REQUEST_DISCOVERABLE); it is an Asynchronous Method to search for a bluetooth device using the startDiscovery () method of the descrithadapter. The method returns immediately after the call. This method searches for other Bluetooth devices for 12 seconds. After this method is called, the search process is actually performed in a System Service, so you can call the cancelDiscovery () method to stop the search (this method can be called when the discovery request is not executed ). After a request for Discovery, the system starts searching for the bluetooth device. During this process, the system sends the following three broadcasts: ACTION_DISCOVERY_START: start searching ACTION_DISCOVERY_FINISHED: search ends ACTION_FOUND: Find the device, the Intent contains two extra fields: EXTRA_DEVICE and EXTRA_CLASS, which respectively include the extra device and the extra thclass. We can register the corresponding BroadcastReceiver to receive the broadcast of the response, so as to implement some functions to view the source code printing? 01 // create a BroadcastReceiver 02 private final BroadcastReceiver () {03 public void onReceive (Context context, Intent intent) {04 String action = intent. getAction (); 05 // device found 06 if (descrithdevice. ACTION_FOUND.equals (action) {07 // get the device object from Intent 08 bytes thdevice device = intent. getParcelableExtra (effecthdevice. EXTRA_DEVICE); 09 // enter the device name and address Array adapter to display 10 mArrayAdapter in ListView. add (device. getName () + "\ n" + device. getAddress (); 11} 12} 13}; 14 // register BroadcastReceiver 15 IntentFilter filter = new IntentFilter (effecthdevice. ACTION_FOUND); 16 registerReceiver (mReceiver, filter); // do not forget to unbind the following code: the program enables Bluetooth, scans the paired bluetooth device, sets the device visibility (time settings), scans the surrounding bluetooth device (within 10 meters), and disables the Bluetooth operation. The specific implementation code is as follows: [java] public class MainActivity extends Activity {private Button button; private Button button2; private Button button3; private Button button4; private Button button5; private javasthadapter adapter; private incluthreceiver extends threceiver; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); bu Tton = (Button) findViewById (R. id. button); button2 = (Button) findViewById (R. id. button1); button3 = (Button) findViewById (R. id. button_display); button4 = (Button) findViewById (R. id. button_scan); button5 = (Button) findViewById (R. id. button_open); // obtain the bluetooth device of the device. If no Bluetooth device exists, null adapter = descrithadapter is returned. getdefaadapter adapter (); // sets the filter to detect the IntentFilter intentFilter = new IntentFilter (effecthdevice. ACTION_FOUND); // generate Broadcast Recipient. When a bluetooth device is found, the Android system sends a broadcast event named threceiver = new thterer (); // registers the broadcast listener registerReceiver (intentFilter ); // obtain the paired bluetooth device. The device information is stored in the memory. setOnClickListener (new OnClickListener () {@ Override public void onClick (View arg0) {// TODO Auto-generated method stub // get the local Bluetooth device, if no Bluetooth exists, the system returns NULL thadapter adapter = descrithadapter. getdefaadapter adapter (); // test whether a bluetooth device exists on the local machine if (ada Pter! = Null) {// obtain the connected bluetooth device, that is, the connected remote Bluetooth device Set <thdevice> devices = adapter. getBondedDevices (); if (devices. size ()> 0) {for (Iterator <effecthdevice> iterator = devices. iterator (); iterator. hasNext ();) {effecthdevice = (effecthdevice) iterator. next (); Log. d ("BruceZhang", effecthdevice. getAddress () ;}} else {Log. d ("BruceZhang", "this device does not have a bluetooth device... ") ;}}); // Disable the Bluetooth operation button2.setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// TODO Auto-generated method stub %thadapter adapter = %thadapter. getdefaadapter adapter (); if (adapter! = Null) {if (adapter. isEnabled () {adapter. disable (); Log. d ("BruceZhang", "the device is disabled... ");} Else {Log. d (" BruceZhang "," the device has been disabled and no operation is required... ") ;}} Else {Log. d (" BruceZhang "," this device does not have a bluetooth device... ") ;}}});/** Bluetooth visibility setting * 1. the visibility of the configured local device, that is, whether the device can be scanned to * 2 by another bluetooth device. the default duration of Bluetooth visibility is 120 seconds. Here, it is modified to 180 seconds for reference */button3.setOnClickListener (new OnClickListener () {@ Override public void onClick (View arg0) {// TODO Auto-generated method stub Intent discoverableIntent = new Intent (effecthadapter. ACTION_REQUEST_DISCOVERABLE); discoverableIntent. putExtra (effecthadapter. EXTRA_DISCOVERABLE_DURATION (180); startActi Discovery (discoverableIntent) ;}}); // scan a remote Bluetooth device using the startDiscovery () method of the descrithadapter to search for a bluetooth device // startDiscovery () the method is an asynchronous method that is returned immediately after being called. This method searches for other Bluetooth devices for 12 seconds. // After this method is called, the search process is actually performed in a System Service. // you can call cancelDiscovery () method To stop the search (this method can be called when the discovery request is not executed ). // After a request for disish, the system starts searching for the bluetooth device. During this process, the system sends the following three broadcasts: // ACTION_DISCOVERY_START: start searching // ACTION_DISCOVERY_FINISHED: end of the search // ACTION_FOUND: Find the device. The Intent contains two extra fields: // EXTRA_DEVICE and EXTRA_CLASS, which respectively include device and thclass. Button4.setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// TODO Auto-generated method stub // a broadcast notification adapter is sent when a bluetooth device is found. startDiscovery (); Log. d ("BruceZhang", "scanning visible Bluetooth devices... ") ;}}); // Enable the bluetooth device button5.setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// TODO Auto-generated method stub if (adapter! = Null) {if (! Adapter. isEnabled () {final Intent intent = new Intent (effecthadapter. ACTION_REQUEST_ENABLE); startActivity (intent); Log. d ("BruceZhang", "the bluetooth device is on... ") ;}} Else {Log. d (" BruceZhang "," this device does not have bluetooth... ") ;}}) ;}// Broadcast receiver. When a remote Bluetooth device is found, the callback function onReceiver () private class extends threceiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {// TODO Auto-generated method stub if (incluthdevice. ACTION_FOUND.equals (intent. getAction () {descrithdevice device = intent. getParcelableExtra (effecthdevice. EXTRA_DEVICE); Log. d ("BruceZhang", "scan to a bluetooth device that can be connected:" + device. getAddress () ;}}@ Override protected void onDestroy () {// TODO Auto-generated method stub super. onDestroy (); unregisterReceiver (effecthreceiver) ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. activity_main, menu); return true ;}}

Related Article

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.