Bluetooth module for Android 4.42-Settings source code analysis

Posted by vishi83 on Thu, 30 May 2019 23:25:30 +0200

Summary of Bluetooth Module


ONE, SWITCH Bluetooth Switch

The process of switch ing from creation to action status monitoring is as follows

  • Create a switch instance

  1. Switch actionBarSwitch = new Switch(activity);  

  • Add instances to actionbar

  1. activity.getActionBar().setCustomView(............);  


  • Pass the switch instance to the Bluetooth Enabler instance by constructive method

  1. mBluetoothEnabler = new BluetoothEnabler(activity, actionBarSwitch);  

  • Call the method of adding menu in fragment

  1. setHasOptionsMenu(true);  

  • Call resume method on instance of Bluetooth Enabler in onResume method

The above series of codes are in Bluetooth Settings. Java This is done in Bluetooth Enabler. java.

  • To determine whether Bluetooth is available or not, set the switch to non-clickable
  • Update switch status according to local Bluetooth status
  • Register and filter the broadcasting of Bluetooth Adapter. ACTION_STATE_CHANGE to update the switch status when the Bluetooth status changes
  • Add listening events to switch, change the local Bluetooth adapter, and update the switch status when the local Bluetooth adapter changes

In summary, the logical implementation of switch is all about creating switch instances in Bluetooth Settings, monitoring and updating the status of switch in Bluetooth Enabler. java, it is not difficult to find that Bluetooth Enabler. Java class is a special class for switching processing.


TWO, Local Bluetooth Related

  • Create preference for local Bluetooth

  1. mMyDevicePreference = new Preference(getActivity());  

  • Display to screen

  1. preferenceScreen.addPreference(mMyDevicePreference);  

  • Constructing an instance of Bluetooth Discoverable Enabler to display and update the subtitle summary of mMyDevice Preference

  1. mDiscoverableEnabler = new BluetoothDiscoverableEnabler(getActivity(),  
  2.                                 mLocalAdapter, mMyDevicePreference);  
  3.                         mDiscoverableEnabler.resume();  

The above code is completed in Bluetooth Settings. The preference includes title -- Bluetooth name, summary -- updates of Bluetooth detectability.

Bluetooth Name - The update process of title is completed in Bluetooth Settings. java. The process is as follows

  • Get the native Bluetooth name

  1. mMyDevicePreference.setTitle(mLocalAdapter.getName());  

  • Pop-up dialog box for Bluetooth renaming operation

  1. new BluetoothNameDialogFragment().show(  
  2.                         getFragmentManager(), "rename device");  

In Bluetooth NameDialogFragment. java, listen for the edit box in the dialog box, and if edited, change the name of the local Bluetooth, which is dedicated to renaming the native Bluetooth.

  1. mLocalAdapter.setName();  

After the current activity pop-up dialog disappears, the program will not execute the onResume method, so register broadcasting in Bluetooth Settings. Java

  • When the local Bluetooth name changes, it sends a broadcast of Bluetooth Adapter. ACTION_LOCAL_NAME_CHANGED. Bluetooth Settings. Java updates the title of mMyDevicePreference after listening to the broadcast.

Bluetooth Detectability - Update Display of Summy

The display update for summary is done in Bluetooth Discoverable Enabler. java, which is dedicated to updating summary and handling click events for mMyDevice Preference

  • Registered broadcasting monitors the change of Bluetooth scanning status. When Bluetooth scanning status changes, it sends Bluetooth Adapter. SCAN_MODE_CONNECTABLE_DISCOVERABLE broadcasting, updates summary and displays it, and calls the method of the third step.
  • Set up click listener for preference and change scan status
  • Show summary according to the scanning status of local Bluetooth

There are two situations when summary is displayed.

If the local Bluetooth can be scanned and detected, that is, in the state of SCAN_MODE_CONNECTABLE_DISCOVERABLE, it will be displayed according to the length of detectability time. The display content is: all nearby devices can detect + timeout.

II > If it is in another state, it should be displayed as "visible to paired devices" or "invisible to all devices" depending on whether a paired device already exists.

Now that we're talking about detectability, let's just say detectable time. When the program starts, we register the broadcasting Bluetooth Discoverable Time out Receiver. When the detectable time is over, we set Bluetooth's scanning state to Bluetooth Adapter. SCAN_MODE_CONNECTABLE, which cancels the detectability of all devices.

  1. localBluetoothAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE);  
When the detectability is fixed for a certain period of time, an alarm clock will be set to trigger broadcasting. When the specified time arrives, the broadcasting will be triggered, and the detectability of Bluetooth mobile phone will be turned off. If you want to be detected permanently, you just need to cancel the alarm clock and not trigger broadcasting.

  1. Intent intent = new Intent(INTENT_DISCOVERABLE_TIMEOUT);  
  2.         intent.setClass(context, BluetoothDiscoverableTimeoutReceiver.class);  
  3.         PendingIntent pending = PendingIntent.getBroadcast(  
  4.             context, 0, intent, 0);  
  5.         AlarmManager alarmManager =  
  6.               (AlarmManager) context.getSystemService (Context.ALARM_SERVICE);  
  7.   
  8.         if (pending != null) {  
  9.             // Cancel any previous alarms that do the same thing.  
  10.             alarmManager.cancel(pending);  
  11.             Log.d(TAG, "setDiscoverableAlarm(): cancel prev alarm");  
  12.         }  
  13.         pending = PendingIntent.getBroadcast(  
  14.             context, 0, intent, 0);  
  15.   
  16.         alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pending);  

Bluetooth detectability is set in Bluetooth Discoverable Timeout Receiver. Java when detectability time arrives. This class is a broadcasting component that is used to turn on or off detectability alarm clock timing and turn off detectability.


THREE, device list related

Add a list of paired settings

  • Create a PreferenceCategory type to pair device list objects mPairedDevicesCategory

  1. mPairedDevicesCategory = new PreferenceCategory(getActivity());  

  • Add the list of pairable devices mPaired Devices Category

  1. addDeviceCategory(mPairedDevicesCategory,  
  2.                         R.string.bluetooth_preference_paired_devices,  
  3.                         BluetoothDeviceFilter.BONDED_DEVICE_FILTER);  


  • Call the following method to pass the list of pairable devices to DeviceList Preference Fragment for management

  1. setDeviceListGroup(preferenceGroup);  

The above code is done in Bluetooth Settings, and then manages the list in DeviceList Preference Fragment

  • Get a list of device caches, which store paired devices and unpaired devices. After successful installation of the program, the paired devices will be read to the cache list through Bluetooth Adapter's getBondedDevices method.
  • Adding paired devices to the list adds preferences constructed for Bluetooth Device preference, which means that preferences for individual devices are managed in Bluetooth Device preference

Add a list of available devices nearby

  • Click on the device available near the scan
  • Display a list of nearby available devices to the screen

  1. getPreferenceScreen().addPreference(mAvailableDevicesCategory);  

  • Scanning to the device, caching to the cache list, and then displaying to the list of available devices nearby
  • If the list of available devices nearby is empty, remove it

The click event of the device is handled in Bluetooth Device Preference, and the action is different if the device is in different state: if the device is paired, the connection will be made after clicking, if the device is paired after clicking, and if the device is connected, the connection will be disconnected after clicking.


Here is a detailed explanation.


===========================================

Bluetooth Module Bluetooth Overview (Part I)


Next, I will introduce the source code of a module in the settings. This article is still based on Android 4.42 source code for analysis and analysis of the implementation of Bluetooth module. It is suggested to take a general look at the analysis of Settings.


ZERO, Bluetooth Module fragment and Its Configuration

Settings_headers.xml file shows that Bluetooth's corresponding fragment is Bluetooth Settings. Java The corresponding id, icon, title, no more details, you can view the xml file by yourself.


  1. <!-- Bluetooth -->  
  2.     <header  
  3.         .......  
  4.         android:fragment="com.android.settings.bluetooth.BluetoothSettings"  
  5.         ......./>  
2>, the list configuration file involved in the property details, the list file describes the Bluetooth interface start-up related settings, such as shortcut entries, and whether to hide the process, etc., here roughly explain some of the unusual attributes, for easy reference.

  1. <activity android:name="......"  
  2.                 android:uiOptions="splitActionBarWhenNarrow"  
  3.                 android:configChanges="orientation|keyboardHidden|screenSize"  
  4.                 android:label="@string/bluetooth_settings_title"  
  5.                 android:taskAffinity=""  
  6.                 android:excludeFromRecents="true">  
  7.             <intent-filter>  
  8.                ......  
  9.             </intent-filter>  
  10.             <meta-data android:name="com.android.settings.FRAGMENT_CLASS"  
  11.                 android:value="com.android.settings.bluetooth.BluetoothSettings" />  
  12.             <meta-data android:name="com.android.settings.TOP_LEVEL_HEADER_ID"  
  13.                 android:resource="@id/bluetooth_settings" />  
  14.         </activity>  
  15.   
  16.         <!-- Keep compatibility with old shortcuts. -->  
  17.         <activity-alias android:name=".bluetooth.BluetoothSettings"  
  18.                   
  19.                 android:label="@string/bluetooth_settings_title"  
  20.                 android:targetActivity="Settings$BluetoothSettingsActivity"  
  21.                 android:exported="true"  
  22.                 android:clearTaskOnLaunch="true">  
  23.             <meta-data android:name="com.android.settings.FRAGMENT_CLASS"  
  24.                 android:value="com.android.settings.bluetooth.BluetoothSettings" />  
  25.             <meta-data android:name="com.android.settings.TOP_LEVEL_HEADER_ID"  
  26.                 android:resource="@id/bluetooth_settings" />  
  27.         </activity-alias>  

You can see that Bluetooth involves two active nodes, one is activity, and the other is activity-alias (an alias for activity, which is used for compatibility with the old version of the shortcut).

  • Android: uiOptions = "split Action Bar When Narrow" // About the configuration of the navigation bar actionbar, where controls are automatically displayed at the bottom of the screen when the screen width is insufficient
  • Android: configChanges= "orientation | keyboard Hidden | screensize" // / is used to prohibit horizontal and vertical screen switching. There are several problems to be addressed. First, if this property is not set, each life cycle will be re-invoked when the screen is cut, once when the screen is cut, twice when the screen is cut. Second, if the attribute android: configChanges= "orientation | keyboard Hidden" is set, the lifecycle will not be re-invoked and only the onConfiguration Changed method will be executed. Thirdly, the second argument is valid only if the Android version is less than 3.2, and if it is higher than that version, screen size must be added to the attribute before it works.
  • android:taskAffinity="// is used to specify the stack to enter after the activity is created. If this property is not specified, the stack specified under the application node is followed, and if the application is not specified, the default package is.
  • android:excludeFromRecents="true"// is displayed in the list of recently launched programs, set to true to indicate that it is not displayed. Mobile phone long press home key to see the latest program list, with this property can hide the process
  • You can see a <activity-alias. /> node juxtaposed with activity. The node belongs to the alias of activity, and the target activity will not cover the attributes under the node. Moreover, the attributes set for the target activity will automatically be added to the activity-alias node. That is to say, Bluetooth module meets the attributes under the two nodes. The reason why the alias is set is mainly for compatibility with the old shortcuts.
  • Android: targetActivity = "Settings $Bluetooth Settings Activity" // Enter the initiated activity by shortcut
  • Android: export= "true"// / Does it support other application calls to start the activity, true is.

Two privileges about Bluetooth are added, BLUETOOTH and BLUETOOTH_ADMIN. The former is mainly used to allow the connection with the matched Bluetooth devices after pairing, while the latter is used to allow the discovery and pairing of Bluetooth devices, mainly the privileges before pairing.

All right, the attribute configuration is introduced here. Next, we need to really start learning the Bluetooth module. First, we need to make clear the layout of the module, the function of the Bluetooth module. Bluetooth implements the following: opening Bluetooth, Bluetooth renaming, Bluetooth detection and detection time settings, scanning nearby Bluetooth devices, loading matched Bluetooth devices, matching with devices, connecting and communicating.


ONE, Bluetooth Layout Implementation

  1. public final class BluetoothSettings extends DeviceListPreferenceFragment {  
  2.   
  3.   
  4. .............  
  5.         @Override  
  6.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  7.                 Bundle savedInstanceState) {  
  8.         addPreferencesFromResource(R.xml.bluetooth_settings);  
  9.       }  
  10.   
  11. ............  
  12. }  

1>, you can see that Bluetooth Settings belongs to Preference Fragment and the layout file to be loaded is Bluetooth_settings.xml file. Following is the layout file code, a total of four lines, the node is Preference Screen, representing the display of the entire screen, the internal can be nested with different types of labels, there is no label here, is the dynamic addition of different types of layout in the code.

  1. <PreferenceScreen  
  2.     xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:title="@string/bluetooth_settings" >  
  4. </PreferenceScreen>  
    

2 > Show two Bluetooth layout sketches on and off


                               


  • Circle 1: The navigation bar at the top of ActionBar displays title and Bluetooth switch. The add code of the switch is in the addPreferences ForActivity method.

  1. @Override  
  2.     void addPreferencesForActivity() {  
  3.         Activity activity = getActivity();  
  4.   
  5.         //Create Bluetooth Switch Control  
  6.         Switch actionBarSwitch = new Switch(activity);  
  7.   
  8.         if (activity instanceof PreferenceActivity) {  
  9.             PreferenceActivity preferenceActivity = (PreferenceActivity) activity;  
  10.             if (preferenceActivity.onIsHidingHeaders() || !preferenceActivity.onIsMultiPane()) {  
  11.                 final int padding = activity.getResources().getDimensionPixelSize(  
  12.                         R.dimen.action_bar_switch_padding);  
  13.                 actionBarSwitch.setPaddingRelative(00, padding, 0);  
  14.                 //Used to lay out the top navigation bar. The top navigation bar displays icons and title on the left.  
  15.                activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,  
  16.                         ActionBar.DISPLAY_SHOW_CUSTOM);  
  17.                 //The top navigation bar shows the switch on the right. The control is adaptive in width and height and centered vertically.  
  18.                activity.getActionBar().setCustomView(actionBarSwitch, new ActionBar.LayoutParams(  
  19.                         ActionBar.LayoutParams.WRAP_CONTENT,  
  20.                         ActionBar.LayoutParams.WRAP_CONTENT,  
  21.                         Gravity.CENTER_VERTICAL | Gravity.END));  
  22.             }  
  23.         }  
  24.          //Pass the switch control to Bluetooth Enabler. Used to update the switch status of Bluetooth  
  25.         mBluetoothEnabler = new BluetoothEnabler(activity, actionBarSwitch);  
  26.          //Tell options menu that fragment wants to add menu items  
  27.         setHasOptionsMenu(true);  
  28.     }  


So how can the initial state of the switch control be obtained? Entering the BluetoothEnabler.java class, you can see that there is a setting for the switch in the resume method of that class.



The handleStateChanged method is to import the current Bluetooth state and set the switch state.

The default value of the switch state is def_bluetooth_on after the mobile phone restores its factory settings. The boolean value corresponding to the default value is saved through Bluetooth Manager Service during the boot process, and the current Bluetooth state is acquired by the local Bluetooth adapter and transmitted to the switch switch switch.

So if you want to change the Bluetooth default switch, you can modify the corresponding fields in the framework / base / packages / Settings Provider / RES / values / default. xml.

  • Circle 2: The bottom bar of ActionBar allows you to search for Bluetooth devices, detect time, list of paired devices and other settings besides pairing. The layout of ActionBar is in the onCreate Options Menu method. Actionbar can be customized by using the following code

  1. menu.add(groupId, itemId, order, title)  
  2. nbsp;.setEnabled(enabled)  
  3.  .setShowAsAction(actionEnum);  
         

group_id: int value, which represents the meaning of a group

item_id: int value, unique identifier for each menu option

order_id: int value, the order in which the menu is displayed, if 0, the order in which the menu is displayed is in add order

Title: charsequence number, title of menu item

setEnabled(enable): Used to set whether clickable or not

SetShowAsAction (Action Enum): Used to set the display of item with different screen widths. Action Enum has the following values.

  • Circle 3: When Bluetooth is not open, preferences creen has no category, emptyview of listview

  1. getListView().setEmptyView(mEmptyView);  

  • Circle 4: The relevant settings of Bluetooth devices, including the name of Bluetooth, the visibility of Bluetooth to nearby available devices, and the visibility of Bluetooth to paired devices. When Bluetooth is detected, a Preference of Bluetooth information will be added, which can be added or removed in method updateContent. The added code is as follows:

  1. if (mMyDevicePreference == null) {  
  2.               //Create a Preference  
  3.               mMyDevicePreference = new Preference(getActivity());  
  4.                }  
  5.                 //The following code is used to set the title, icon, and clickability of Preference.  
  6.              mMyDevicePreference.setTitle(mLocalAdapter.getName());  
  7.               
  8.                if (getResources().getBoolean(com.android.internal.R.bool.config_voice_capable)) {  
  9.                  //If it's a cell phone, display the icon of the cell phone.  
  10.                    mMyDevicePreference.setIcon(R.drawable.ic_bt_cellphone);    // for phones  
  11.                } else {  
  12.                 //If not for mobile phones such as laptops, microcontrollers with Bluetooth modules, then display computer icons  
  13.                  mMyDevicePreference.setIcon(R.drawable.ic_bt_laptop);   // for tablets, etc.  
  14.                }  
  15.                //Whether to write the value of the Preference to the SharedPreference file, true represents writing  
  16.                mMyDevicePreference.setPersistent(false);  
  17.                //Is it clickable  
  18.               mMyDevicePreference.setEnabled(true);  
  19.              //Add a Preference  
  20.               preferenceScreen.addPreference(mMyDevicePreference);  

                 

The code added or removed by preferences creen is as follows:

  1. //Add a kind of Preference  
  2. getPreferenceScreen().addPreference(mAvailableDevicesCategory);  
  3. .,....  
  4. //Remove a Preference  
  5. preferenceScreen.removePreference(mPairedDevicesCategory);  
  6. .....  
  7. //Remove all  
  8. Preference preferenceScreen.removeAll();  


  • Circle 5: Matched Devices List mPaired Devices Category
  • Circle 6: List of nearby available devices mAvailable Devices Category

In general, Bluetooth layout is implemented by actionbar+Preference, which is dynamically added to the code. The addition of Actionbar is implemented in methods addPreferences ForActivity and onCreate Options Menu. Adding and modifying Bluetooth switch status with reference of different Categories, whether there are matched Bluetooth devices and whether there are available Bluetooth devices nearby.

The layout of Bluetooth interface is introduced here for the time being. If you have any questions, leave a message in your blog. I'll add it again.

TWO, Brief Introduction of Bluetooth Module Method

After the Bluetooth module is opened, the execution process getHelpResource () ----> addPreferences ForActivity () - - - > onCreateView () - - - > initDevicePreference () - - - > onAcitivityCreated () - > onResume () - - > OptitDevicePreference () - - - > onCreateMenu ().

First of all, I will introduce the function of overwriting method.

1>, getResource() method, defined in the Setting PreferenceFragment. Java class, returns 0 by default. The explanation of the method is that if you want to display help item s on the menu bar, you can override the method for some descriptions (Specified in product overlays).

2>, addPreferences ForActivity () method for adding switch es on actionbar, see Bluetooth Layout section for the code

3>, onCreateView() method, fragment lifecycle method, for loading xml layout

  1. @Override  
  2.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  3.                 Bundle savedInstanceState) {  
  4.         addPreferencesFromResource(R.xml.bluetooth_settings);  
  5.         View v = inflater.inflate(R.layout.add_preference_list_fragment,null);  
  6.         mEmptyView = (TextView) v.findViewById(R.id.add_empty);  
  7. }  


4>, initDevicePreference() method to get the matched Bluetooth device and set up the listening event

  1. @Override  
  2.     void initDevicePreference(BluetoothDevicePreference preference) {  
  3.         CachedBluetoothDevice cachedDevice = preference.getCachedDevice();  
  4.         if (cachedDevice.getBondState() == BluetoothDevice.BOND_BONDED) {  
  5.             // Only paired device have an associated advanced settings screen  
  6.            //If the device has been paired, add listening events  
  7.            preference.setOnSettingsClickListener(mDeviceProfilesListener);  
  8.         }  
  9.     }  

5>, onDevicePreferenceClick() method, click events for remote Bluetooth devices

  1. @Override  
  2.    void onDevicePreferenceClick(BluetoothDevicePreference btPreference) {  
  3.       //Stop scanning  
  4.      mLocalAdapter.stopScanning();  
  5.       //Click events calling parent classes  
  6.       super.onDevicePreferenceClick(btPreference);  
  7.    }  

6>, onBluetoothStateChanged() method, monitor when Bluetooth switch state changes

7>, onScanning StateChanged () method, which monitors the status changes of the scan when scanning Bluetooth devices are available, opens the scan, is scanning, ends the scan, and updates the progress bar


THREE, Bluetooth Function Implementation Process

Function module is mainly to analyze the process of implementation, code as a supplement, if you look at the source code time code problems, you can consult under the blog.

Bluetooth switch is related.

Bluetooth switch involves the change of local Bluetooth state and the change of Bluetooth state when the user clicks on the switch. When the local Bluetooth state changes, the state of the switch needs to be updated. When the state of the switch changes, the local Bluetooth state needs to be updated. This involves the way registered broadcasting monitors the local Bluetooth state, changes to the switch for the switch registered listener, and settings for the switch state.

First, add Preferences ForActivity is executed to load the switch. In this method, Bluetooth Enabler object is constructed to initialize the state of the switch and monitor the state change.

Next, the Bluetooth Enabler is analyzed. Let's first look at how Bluetooth Enabler is constructed.

  1. public BluetoothEnabler(Context context, Switch switch_) {  
  2.        mContext = context;  
  3.        mSwitch = switch_;  
  4.        mValidListener = false;  
  5.         
  6.      //First, determine whether Bluetooth is supported or not.  
  7.      LocalBluetoothManager manager = LocalBluetoothManager.getInstance(context);  
  8.        if (manager == null) {  
  9.            //Bluetooth is not supported. Bluetooth local adapter is null and switch state is unchecked  
  10.          mLocalAdapter = null;  
  11.            mSwitch.setEnabled(false);  
  12.        } else {  
  13.            //If Bluetooth is supported to access the local Bluetooth adapter,  
  14.           mLocalAdapter = manager.getBluetoothAdapter();  
  15.        }  
  16.           //Bluetooth Switch State Filter  
  17.         mIntentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);  
  18.       
  19.    }  
Next, the Bluetooth switch state is set in resume().

  1. public void resume() {  
  2.         if (mLocalAdapter == null) {  
  3.             //If the Bluetooth adapter is empty, the resume method is returned without any remaining operations in the resume method.  
  4.            mSwitch.setEnabled(false);  
  5.             return;  
  6.         }  
  7.   
  8.         // Bluetooth state is not sticky, so set it manually  
  9.        //You have to monitor Bluetooth state manually  
  10.         //According to the local Bluetooth adapter to get the status of Bluetooth at this time, the switch is set up.  
  11.        handleStateChanged(mLocalAdapter.getBluetoothState());  
  12.            
  13.         //Registered Broadcasting Monitors Changes in Bluetooth State  
  14.         mContext.registerReceiver(mReceiver, mIntentFilter);  
  15.         //Setting up listening events for switch  
  16.        mSwitch.setOnCheckedChangeListener(this);  
  17.         mValidListener = true;  
  18.     }  

Three things are done in the resume method.

I > Setting handleStateChanged(state) method code for switch ing based on the Bluetooth state acquired by the local Bluetooth adapter is very simple and will not be repeated.

II >, registered broadcasting monitors Bluetooth status - when the Bluetooth status of the system changes, the switch status needs to be updated. The code in the broadcasting receiver is as follows

  1. private final BroadcastReceiver mReceiver = new BroadcastReceiver() {  
  2.         @Override  
  3.         public void onReceive(Context context, Intent intent) {  
  4.             // Broadcast receiver is always running on the UI thread here,  
  5.             // so we don't need consider thread synchronization.  
  6.             int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);  
  7.              //Setting switch for different Bluetooth States  
  8.             handleStateChanged(state);  
  9.         }  
  10.     };  

III >, set up a monitor event for the switch, when the switch changes, the Bluetooth state of the system needs to be changed. When the Bluetooth switch state of the system changes, it will send the broadcast of the state change to change the switch.

  1. public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {  
  2.   
  3.        // shouldn't setBluetoothEnabled(true) in airplane mode.  
  4.      //Bluetooth is unavailable in flight mode  
  5.     if (mLocalAdapter != null) {  
  6.            if (isChecked && WifiSettings.needPrompt(mContext)) {  
  7.                return;  
  8.            }  
  9.          //When the switch switch switch state changes, the local Bluetooth state of the system is set.  
  10.          mLocalAdapter.setBluetoothEnabled(isChecked);  
  11.        }  
  12.    //When the switch state changes, make it non-clickable  
  13.     mSwitch.setEnabled(false);  
  14.    }  

Next, let's look at how to change the local Bluetooth adapter

  1. public void setBluetoothEnabled(boolean enabled) {  
  2.        //Turn Bluetooth on or off according to switch enable, and succeed returns the execution result.  
  3.         boolean success = enabled  
  4.                 ? mAdapter.enable()  
  5.                 : mAdapter.disable();  
  6.         isPairing = false;  
  7.         if (success) {  
  8.            //If Bluetooth on or off of the system is successful, update the status  
  9.             setBluetoothStateInt(enabled  
  10.                 ? BluetoothAdapter.STATE_TURNING_ON  
  11.                 : BluetoothAdapter.STATE_TURNING_OFF);  
  12.         } else {  
  13.            //If Bluetooth is not turned on or off successfully, the Bluetooth status is updated and saved as Bluetooth status of the current system.  
  14.             syncBluetoothState();  
  15.         }  
  16.     }  
Bluetooth Adapter's enable method is used to turn on Bluetooth and disable to turn off Bluetooth.

2>, Bluetooth settings, including detectability, Bluetooth name, detectable time.

I >, load Bluetooth related information

In the updateContent method, preference (single control, similar to checkbox) or preference category (combination control, similar to linearlayout) are added dynamically. The native Bluetooth message adds a preference

  1. if (mMyDevicePreference == null) {  
  2.                     mMyDevicePreference = new Preference(getActivity());  
  3.                 }  
  4.                //Set the title title title of preference to show the Bluetooth name  
  5.                mMyDevicePreference.setTitle(mLocalAdapter.getName());  
  6.         //If it's a mobile phone, the icon is set to the icon of the mobile phone, if it's a tablet or something, it's set to the icon of the computer.  
  7.                 if (getResources().getBoolean(com.android.internal.R.bool.config_voice_capable)) {  
  8.                     mMyDevicePreference.setIcon(R.drawable.ic_bt_cellphone);    // for phones  
  9.                 } else {  
  10.                     mMyDevicePreference.setIcon(R.drawable.ic_bt_laptop);   // for tablets, etc.  
  11.                 }  
  12.                 //Whether to save the preference information in shared Preference  
  13.                mMyDevicePreference.setPersistent(false);  
  14.                 //Setting preference clickable  
  15.                mMyDevicePreference.setEnabled(true);  
  16.                 //Add mMyDevicePreference  
  17.                 preferenceScreen.addPreference(mMyDevicePreference);  
  18.   
  19.                 if (!isRestrictedAndNotPinProtected()) {  
  20.                     if (mDiscoverableEnabler == null) {  
  21.                         mDiscoverableEnabler = new BluetoothDiscoverableEnabler(getActivity(),  
  22.                                 mLocalAdapter, mMyDevicePreference);  
  23.                         //Setting up Bluetooth Detectability  
  24.                          mDiscoverableEnabler.resume();  
  25.                         LocalBluetoothManager.getInstance(getActivity()).setDiscoverableEnabler(  
  26.                                 mDiscoverableEnabler);  
  27.                     }  
  28.                 }  
  29.                   <pre name="code" class="java">                // Paired devices category  
  30.                 //Load the list of matched devices  
  31.               if (mPairedDevicesCategory == null) {  
  32.                     mPairedDevicesCategory = new PreferenceCategory(getActivity());  
  33.                 } else {  
  34.                     mPairedDevicesCategory.removeAll();  
  35.                 }  
  36.                 addDeviceCategory(mPairedDevicesCategory,  
  37.                         R.string.bluetooth_preference_paired_devices,  
  38.                         BluetoothDeviceFilter.BONDED_DEVICE_FILTER);  
  39.                 //Getting the number of devices that have been paired relates to the summary text displayed by mMyDevice Preference  
  40.                int numberOfPairedDevices = mPairedDevicesCategory.getPreferenceCount();  
  41.                 if (mDiscoverableEnabler != null) {  
  42.                          //Processing the displayed summary based on the number of pairs  
  43.                          mDiscoverableEnabler.setNumberOfPairedDevices(numberOfPairedDevices);  
  44.                 }  
 

II >, Modify Bluetooth Name

The button to modify the Bluetooth name is MENU_ID_RENAME_DEVICE in the menu bar. The process is to assign the Bluetooth name to the Bluetooth adapter of the system after modification. The Bluetooth adapter of the system sends a broadcast notification that the Bluetooth name has been modified, and updates the title of preference after receiving the broadcast with the modified Bluetooth name. The code flow is as follows

  1.  public boolean onOptionsItemSelected(MenuItem item) {  
  2.           ........  
  3.             case MENU_ID_RENAME_DEVICE:  
  4.               //Pop up the modified dialog box and call the method to modify the Bluetooth name when clicking OK.  
  5.                
  6.                 new BluetoothNameDialogFragment().show(  
  7.                         getFragmentManager(), "rename device");  
  8.                 return true;  
  9.                 ......  
  10. }  

When the Bluetooth name changes, a broadcast notification will be sent that the Bluetooth name has changed and the preference will be updated. It is emphasized here that as long as the edit box in the dialog box is edited, whether the content is modified (such as deleting and adding the same one after deletion), the broadcast with the changed Bluetooth name will be sent. So far, the modification of Bluetooth name has been completed.

III >, Modification of Bluetooth Detectability

Popularizing a knowledge first helps to understand the detectability of Bluetooth. Bluetooth Adapter's getScanMode has three values, meaning

SCAN_MODE_NONE, int value, size 20, means that it is invisible to any device and cannot be scanned.

SCAN_MODE_CONNECTABLE, int value, size 21, indicates that only paired devices are visible and other devices can be scanned.

SCAN_MODE_CONNECTABLE_DISCOVERABLE, with an int value of 23, indicates that it is visible to all nearby devices and can scan other devices.

The detectability of Bluetooth is determined by the getScanMode () of Bluetooth Adapter, the scanning mode of local bluetooth, so the detectability of Bluetooth is first displayed in the summary subtitle of mMyDevicePreference, and then the update of the subtitle is located in the Bluetooth Discoverable Enabler class, in which the broadcasting is first registered to monitor the local Bluetooth scanning mode. change

  1. private final BroadcastReceiver mReceiver = new BroadcastReceiver() {  
  2.        @Override  
  3.        public void onReceive(Context context, Intent intent) {  
  4.            //Monitoring Bluetooth Scanning Mode Change  
  5.             if (BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(intent.getAction())) {  
  6.                int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE,  
  7.                        BluetoothAdapter.ERROR);  
  8.                if (mode != BluetoothAdapter.ERROR) {  
  9.                  //If the scan mode changes and no errors occur, update the subtitle  
  10.                   handleModeChanged(mode);  
  11.                }  
  12.            }  
  13.        }  
  14.    };  

The way to update the subtitle is as follows, because there are three modes, so there are also three situations for the subtitle.

  1. void handleModeChanged(int mode) {  
  2.         //Visible and scannable to all nearby devices  
  3.         if (mode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {  
  4.             //Locate the flag as true, related to the click event of the preference  
  5.             mDiscoverable = true;  
  6.           //Update the subtitle according to the time, at which point the subtitle shows the visibility and visibility time of all nearby devices.  
  7.            updateCountdownSummary();  
  8.         } else {  
  9.              
  10.           mDiscoverable = false;  
  11.             //Update the subtitle. If the list of paired devices is empty, it will not be visible to all devices. If the list of paired devices is not empty, it will be visible to paired devices.  
  12.             setSummaryNotDiscoverable();  
  13.         }  
  14.     }  

Then add a click event to preference, reverse the flag when clicking preference, and update the summary of preference and Bluetooth scanning mode.

  1. public boolean onPreferenceClick(Preference preference) {  
  2.         mDiscoverable = !mDiscoverable;  
  3.         setEnabled(mDiscoverable);  
  4.         return true;  
  5.     }  

When updating summary, it involves updating detectability time. Let's talk about implementing logic without code. Ask again if necessary.

Firstly, the detectability event is defined, and then a thread is opened in the method of updating summary after opening the detectability of time limit. The method of updating summary is called again in the thread. Time is judged in the method of updating summary, and if the time is over, it exits the method.

3>, list of paired devices


==========================================================================

Bluetooth Module Bluetooth Overview (Part 2)



Continue the research of Bluetooth module source code


THREE, Implementation of Bluetooth Module Function

The analysis of switch and the renaming and visibility of Bluetooth on this machine can be seen in the previous article. Next, the third part of Chapter 3 introduces the loading of the list of Bluetooth remote devices. If you haven't read it, I suggest that you look at the layout of Bluetooth in Chapter 1 of the previous article, which is helpful to understand.

3>, loading device list

Because there are a lot of codes in this part, I will talk about the idea first. First, the program obtains the list of matched devices through the getBondedDevices() method of Bluetooth Adapter at the bottom. After obtaining the list, it caches the data in List < Cached Bluetooth Device> for backup. When the Bluetooth interface starts, it reads the data from the cache and displays the list of matched devices mPaired Devic. EsCategory, when scanning nearby available devices, will add or delete the data in the cache, and display the data in the list of available devices mAvailable Devices Category, and the program will monitor the status changes of remote devices in real time, increase or delete the list of devices. That's basically what the list of devices loads are, so let's go through them one by one.

I >, call the underlying code to get the list of available devices and cache them

This part of the code is written in Bluetooth Event Manager. Java In the file, the code to get the list of paired devices is defined as follows.

  1. boolean readPairedDevices() {  
  2.        //mLocalAdapter maps Bluetooth Adapter locally, its internal code is no longer written, and it gets paired devices.  
  3.        Set<BluetoothDevice> bondedDevices = mLocalAdapter.getBondedDevices();  
  4.         if (bondedDevices == null) {  
  5.             return false;  
  6.         }  
  7.         boolean deviceAdded = false;  
  8.         for (BluetoothDevice device : bondedDevices) {  
  9.             //This step calls the method findDevice in the management class CachedBluetoothDeviceManager of the device cache list  
  10.             //Used to check if the device already exists in the cache list, return device if it exists, and null if it does not exist  
  11.             CachedBluetoothDevice cachedDevice = mDeviceManager.findDevice(device);  
  12.             if (cachedDevice == null) {  
  13.                 //If there is no device in the cache list, call addDevice in the management class CachedBluetoothDeviceManager  
  14.                 //Add devices to the cache list  
  15.                cachedDevice = mDeviceManager.addDevice(mLocalAdapter, mProfileManager, device);  
  16.               //Update the device to the screen  
  17.                dispatchDeviceAdded(cachedDevice);  
  18.                 deviceAdded = true;  
  19.             }  
  20.         }  
  21.         return deviceAdded;  
  22.     }  

This method is called in two places, one is when the Bluetooth Adapter is turned on, the other is when the state of the remote Bluetooth Device changes.

Here is the code in the Local Bluetooth ProfileManager. Java file. When Bluetooth is turned on, the following code is called to read the matched device

  1. void setBluetoothStateOn() {  
  2.        ParcelUuid[] uuids = mLocalAdapter.getUuids();  
  3.        if (uuids != null) {  
  4.       
  5.            updateLocalProfiles(uuids);  
  6.        }  
  7.        mEventManager.readPairedDevices();  
  8.    }  
When the remote device changes, the broadcast of ACTION_BOND_STATE_CHANGED is sent, and the readPairedDevices () method is called in the registered handler to read the matching device. The code to listen for broadcasting is in Bluetooth EventManager. java.

In fact, after scanning, the list of acquired devices is cached together with the list of matched devices, which is introduced in the introduction section.

II >, device list loaded to screen

Now, both paired devices and nearby available devices are cached in the same list, so the loading of the two lists is similar. When the list of nearby available devices is displayed, there will be a progress, so there is a difference in the construction of preferenceGroup object. Another difference is the state of the device. The remote device is accessed by getBondState() in the underlying Bluetooth Device class. Distinguish states.

The device list is loaded into Bluetooth Settings, the paired device list is mPaired Devices Category, and the nearby available device list is mAvailable Devices Category. They are all Preference Category objects. When loading, the addDevice Category (Preference Group preference, int Title Id, Bluetooth Device Filter. Filter) in Bluetooth Settings. Java is called. Filter method.

The filter set by the paired device is Bluetooth DeviceFilter. BONDED_DEVICE_FILTER

The filter set by the nearby available device is Bluetooth DeviceFilter. UNBONEDE_DEVICE_FILTER


  1. private void addDeviceCategory(PreferenceGroup preferenceGroup, int titleId,  
  2.             BluetoothDeviceFilter.Filter filter) {  
  3.         //Setting the title of preferenceGroup  
  4.        preferenceGroup.setTitle(titleId);  
  5.       //Add preference group for PreferenceScreen. Note that there is no preference in preference group at this time.  
  6.       getPreferenceScreen().addPreference(preferenceGroup);  
  7.         //Set up the filter and call the method in DeviceList Preference Fragment  
  8.         setFilter(filter);  
  9.        //Call the method in DeviceList PreferencFragment and tell preference group to pass on to facilitate its operation  
  10.         setDeviceListGroup(preferenceGroup);  
  11.         //Calling methods in DeviceList PreferenceFragment  
  12.         addCachedDevices();  
  13.        //Set preference to a clickable state  
  14.         preferenceGroup.setEnabled(true);  
  15.     }  

The addCachedDevices() code is as follows

  1. void addCachedDevices() {  
  2.      //Used to retrieve a copy of the cached list  
  3.      Collection<CachedBluetoothDevice> cachedDevices =  
  4.                 mLocalManager.getCachedDeviceManager().getCachedDevicesCopy();  
  5.         for (CachedBluetoothDevice cachedDevice : cachedDevices) {  
  6.             //This method is used to display the device.  
  7.            onDeviceAdded(cachedDevice);  
  8.         }  
  9.     }  


The onDeviceAdded(cachedDevice) code is as follows

  1. public void onDeviceAdded(CachedBluetoothDevice cachedDevice) {  
  2.         if (mDevicePreferenceMap.get(cachedDevice) != null) {  
  3.             return;  
  4.         }  
  5.   
  6.         // Prevent updates while the list shows one of the state messages  
  7.         if (mLocalAdapter.getBluetoothState() != BluetoothAdapter.STATE_ON) return;  
  8.           //This is the function of the filter. First of all, filter out the required equipment, requiring paired or nearby available equipment.  
  9.           //After the list is filtered, it can be loaded.  
  10.         if (mFilter.matches(cachedDevice.getDevice())) {  
  11.             createDevicePreference(cachedDevice);  
  12.         }  
  13.      }  

With respect to matches methods, you can view Bluetooth DeviceFilter. Java files. Different filters correspond to different internal classes. These internal classes implement matches methods of internal interfaces, matching the matching status of Bluetooth Device. For example, filtering the matched internal classes of Bluetooth Device filters is as follows

  1. //Note that Filter is the internal interface of Bluetooth DeviceFilter  
  2. rivate static final class BondedDeviceFilter implements Filter {  
  3.        public boolean matches(BluetoothDevice device) {  
  4.            return device.getBondState() == BluetoothDevice.BOND_BONDED;  
  5.        }  
  6.    }  

When the cache list is filtered, the createDevicePreference(cachedDevice) method is called to load it if it meets the criteria.

  1. void createDevicePreference(CachedBluetoothDevice cachedDevice) {  
  2.        //Constructing preference objects  
  3.      BluetoothDevicePreference preference = new BluetoothDevicePreference(  
  4.                getActivity(), cachedDevice);  
  5.         //In this method, preference is initialized and can be realized on demand.  
  6.        initDevicePreference(preference);  
  7.        //Display preference  
  8.       mDeviceListGroup.addPreference(preference);  
  9.        mDevicePreferenceMap.put(cachedDevice, preference);  
  10.    }  


This is where the device list is loaded. To sum up, the overall management of preference group, such as adding or deleting preference, is located in the DeviceList Preference Fragment. Java file, but the UI status of preference display in preference group, such as title, summary, icon, is not in this class, but in Bluetooth Device Preference. java. Rationality can be seen from the preference object constructed.


III >, device list changes

When the state of the device changes, the display of the device list also changes, such as matching devices, canceling matching operations, monitoring and processing the state of the device in Bluetooth EvenManager. java. Many monitors are registered in this kind of construction method, monitoring Bluetooth-related changes, such as Bluetooth status change ACTION_STATE_CHANGED, etc., are needed. Look at it.

Here's a brief talk about the various broadcasts

  • Bluetooth Adpater. ACTION_STATE_CHANGED: The Bluetooth state of the local machine has changed
  • Bluetooth Adpater. ACTION_DISCOVERY_STARTED: Start scanning
  • Bluetooth Adpater. ACTION_DISCOVERY_FINISHED: Scan End
  • Bluetooth Device. ACTION_FOUND: Discovering Remote Bluetooth Devices
  • Bluetooth Device. ACTION_DISAPPEARED: Remote Device Disappearance
  • Bluetooth Device. ACTION_NAME_CHANGED: Remote Device Bluetooth Name Change
  • Bluetooth Device. ACTION_BOND_STATE_CHANGED: Remote Device Connection State Change
  • Bluetooth Device. ACTION_PAIRING_CANCLE: Remote Device Unpairing
  • Bluetooth Device. ACTION_CLASS_CHANGED: Bluetooth classes for remote devices have changed
  • BluetoothDevice.ACTION_UUID:

For more information on Bluetooth broadcasting, refer to the online documentation http://www. Android-doc.com/reference/android/bluetooth/BluetoothDevice.html

In the program, listeners have been registered for these broadcasts, and when they receive the broadcasts, they take corresponding actions to modify the list.

First, the cache list is changed, and then the display list is changed.


4>, Bluetooth Search for Available Devices Nearby

The search function flow is as follows: first, check whether Bluetooth is on, if it is on, if it is on, do not process, if it is not on, then open the search.

The settings in the program are that the search device button is not available if Bluetooth is not turned on or searching. If forced search is playing music, etc., search directly. The SCAN_EXPIRATION_MS set in the program is 5 minutes. In one case, the search is over, but the time is not 5 minutes. If the search is not mandatory, the search will not be opened in this case.

  1. void startScanning(boolean force) {  
  2.         // Only start if we're not already scanning  
  3.         if (!mAdapter.isDiscovering()) {  
  4.             if (!force) {  
  5.                 // Don't scan more than frequently than SCAN_EXPIRATION_MS,  
  6.                 // unless forced  
  7.                 if (mLastScan + SCAN_EXPIRATION_MS > System.currentTimeMillis()) {  
  8.                     return;  
  9.                 }  
  10.   
  11.                 // If we are playing music, don't scan unless forced.  
  12.                 A2dpProfile a2dp = mProfileManager.getA2dpProfile();  
  13.                 if (a2dp != null && a2dp.isA2dpPlaying()) {  
  14.                     return;  
  15.                 }  
  16.             }  
  17.   
  18.             if (mAdapter.startDiscovery()) {  
  19.                 mLastScan = System.currentTimeMillis();  
  20.             }  
  21.         }  
  22.     }  
During the search process, it was found that the device would send a broadcast, and the program would update the cache list and display list in the broadcast processing code.

When the scan starts, the broadcasting is sent, handler is processed, and when the scan contacts, the following handler is processed, except that the start is false.

  1. private class ScanningStateChangedHandler implements Handler {  
  2.        private final boolean mStarted;  
  3.       //true is passed in at the beginning of the scan  
  4.        ScanningStateChangedHandler(boolean started) {  
  5.            mStarted = started;  
  6.        }  
  7.        public void onReceive(Context context, Intent intent,  
  8.                BluetoothDevice device) {  
  9.            synchronized (mCallbacks) {  
  10.                for (BluetoothCallback callback : mCallbacks) {  
  11.                         //Call the method in DeviceListPreferenceFragment.java to display the scan indication progress  
  12.                        callback.onScanningStateChanged(mStarted);  
  13.                }  
  14.            }  
  15.            //First update the cache list, and then sort and update the display list.  
  16.            //The collation code is in CachedBluetoothDevice.java  
  17.          mDeviceManager.onScanningStateChanged(mStarted);  
  18.           //This method is used to save the start scan time.  
  19.             LocalBluetoothPreferences.persistDiscoveringTimestamp(context);  
  20.        }  
  21.    }  


When remote devices are found during scanning, the following processing is performed

  1. private class DeviceFoundHandler implements Handler {  
  2.        public void onReceive(Context context, Intent intent,  
  3.                BluetoothDevice device) {  
  4.            //Get the signal strength of Bluetooth, default to the 15 th power of Short type minimum - 2  
  5.            short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);  
  6.            //Get the type of remote device  
  7.             BluetoothClass btClass = intent.getParcelableExtra(BluetoothDevice.EXTRA_CLASS);  
  8.           //Get the name of the remote device  
  9.            String name = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);  
  10.            //After retrieving the remote device, check whether it is in the cache list, return the device if it is, or return null if it is not.  
  11.            CachedBluetoothDevice cachedDevice = mDeviceManager.findDevice(device);  
  12.            if (cachedDevice == null) {  
  13.               //Add devices to the cache list  
  14.               cachedDevice = mDeviceManager.addDevice(mLocalAdapter, mProfileManager, device);  
  15.                // callback to UI to create Preference for new device  
  16.               //Update the added device to the display list  
  17.              dispatchDeviceAdded(cachedDevice);  
  18.            }  
  19.            //Cache device signal strength, device type, name  
  20.            cachedDevice.setRssi(rssi);  
  21.            cachedDevice.setBtClass(btClass);  
  22.            cachedDevice.setName(name);  
  23.            //It's not about setting visibility here, it's about sorting lists.  
  24.           cachedDevice.setVisible(true);  
  25.        }  
  26.    }  


5 >, Bluetooth Matching

The list of devices includes paired devices, unpaired devices, connected devices, etc. When you click preference, you will first determine which state you are in, and then proceed to the next state. If there is no pairing, pair up.

The matching procedure is as follows. When matching, first check whether the remote device is matching. If it is, return true. If not, set the Bluetooth matching status of the local machine to true to indicate that it is matching. Then stop the scanning operation of Bluetooth, pair with the remote device, and automatically connect after matching is successful.

  1. //This method returns true to indicate that the pairing operation is in progress, and false to indicate that the pairing operation failed to pop up the failed pop-up window.  
  2.  boolean startPairing() {  
  3.           //First, check if the remote device is pairing, and if it is pairing, return true.  
  4.           if(mLocalAdapter.checkPairingState() == true)  
  5.         {  
  6.             return true;  
  7.         }  
  8.           //Set the matching state of the native Bluetooth adapter to true  
  9.         mLocalAdapter.setPairingState(true);  
  10.         // Pairing is unreliable while scanning, so cancel discovery  
  11.         //If native Bluetooth is scanning Bluetooth, stop the operation because it will block.  
  12.        if (mLocalAdapter.isDiscovering()) {  
  13.             mLocalAdapter.cancelDiscovery();  
  14.         }  
  15.         //Call the framework layer method to determine whether remote Bluetooth devices can be paired and whether the request pairing is timed out.  
  16.        //If pairing is possible, set the pairing status of remote Bluetooth devices to be in pairing  
  17.       if (!mDevice.createBond()) {  
  18.            //If the pairing with remote Bluetooth device fails, set the native Bluetooth pairing state to false  
  19.            mLocalAdapter.setPairingState(false);  
  20.             return false;  
  21.         }  
  22.        //Whether to connect automatically after pairing, true to connect automatically  
  23.        mConnectAfterPairing = true;  // auto-connect after pairing  
  24.         return true;  
  25.     }  


6>, Bluetooth Connection

Before making a connection, first determine whether it has been paired. If there is no pairing, it will be paired, cancel the operation of the connection, and if it has been paired, make a device connection.

  1. void connect(boolean connectAllProfiles) {  
  2.        //If there is no pairing, pair and exit the connection method  
  3.       if (!ensurePaired()) {  
  4.            return;  
  5.        }  
  6. //Get the time interval from system startup to the present  
  7.        mConnectAttempted = SystemClock.elapsedRealtime();  
  8.       //As you can see from English, it means not to reset the timer when connecting.  
  9.        connectWithoutResettingTimer(connectAllProfiles);  
  10.    }  


Next, take a look at the code for the connectWithoutResettingTimer(connectAllProfiles) method

  1. private void connectWithoutResettingTimer(boolean connectAllProfiles) {  
  2.         // Try to initialize the profiles if they were not.  
  3.         //Configuration specification for native Bluetooth to communicate with remote devices, which cannot communicate without configuration files  
  4.         //The configuration specification specifies the Bluetooth communication protocol used, user interface format, and so on.  
  5.         if (mProfiles.isEmpty()) {  
  6.             Log.d(TAG, "No profiles. Maybe we will connect later");   
  7.             return;  
  8.         }  
  9.   
  10.         // Reset the only-show-one-error-dialog tracking variable  
  11.         //When we go to connect multiple devices with errors, we just want to display an error dialog box.  
  12.        mIsConnectingErrorPossible = true;  
  13.       
  14.         int preferredProfiles = 0;  
  15.         for (LocalBluetoothProfile profile : mProfiles) {  
  16.           
  17.             if (connectAllProfiles ? profile.isConnectable() : profile.isAutoConnectable()) {  
  18.                   
  19.   
  20.                 if (profile.isPreferred(mDevice)) {  
  21.                     ++preferredProfiles;  
  22.             //Connecting devices, you can see details about profile s.  
  23.                     connectInt(profile);  
  24.                       
  25.                 }  
  26.             }  
  27.         }  
  28.         if (DEBUG) Log.d(TAG, "Preferred profiles = " + preferredProfiles);  
  29.   
  30.         if (preferredProfiles == 0) {  
  31.             connectAutoConnectableProfiles();  
  32.         }  
  33.     }  


FOUR, summary

1> First, we summarize some common frameworks layer Bluetooth-related methods.

I >, Local Bluetooth Related

Get the local Bluetooth adapter: Bluetooth Adapter. getDefaultAdapter ();

Turn on Bluetooth: Bluetooth Adapter - enable ().

Turn Bluetooth off: Bluetooth Adapter - disable ().

Rename Bluetooth: Bluetooth Adapter - setName ().

Get the Bluetooth name: Bluetooth Adapter - - getName ().

Turn on detectability: Bluetooth Adapter - setScanMode (Bluetooth Adapter).

SCAN_MODE_CONNECTABLE_DISCOVERABLE, timeout). //When timeout is set to 0, it means never timeout.

Get Bluetooth status: Bluetooth Adapter - getState ().

Get the uuid array supported by Bluetooth: Bluetooth Adapter - - getUuids ().

Get the paired device: Bluetooth Adapter -- getBoneDevices ().

Open Scan: Bluetooth Adapter - StartDiscovery ().

Stop scanning: Bluetooth Adapter - cancelDiscovery ().

Determine whether the scan is in progress: Bluetooth Adapter - is Discovery ().

Scanning low power BLE Bluetooth devices: Bluetooth Adapter - - Start LeScan (mLeScan CallBack).

Stop scanning BLE devices: Bluetooth Adapter - stop LeScan (mLeScan CallBack).


II >, various broadcasting related reference websites, this is an API online document, explained very clearly

http://www.android-doc.com/reference/android/bluetooth/BluetoothDevice.html

2>, the classes involved in Bluetooth module source code

Bluetooth Settings. java: Bluetooth interface display layout fragment, only layout-related, will be the name of the local Bluetooth, detectability real-time updates, all click event processing is elsewhere

II >, DeviceList Preference Fragment: Updates to the display of remote device lists, including paired lists and lists of nearby available devices

III >, Bluetooth Device Preference: Changes to title, summary, icon for each device in the list, including device click events

IV >, Cached Bluetooth Device: Managing remote devices, pairing, connecting



Links to the original text: http://blog.csdn.net/zrf1335348191/article/details/50995466

Topics: Android Java Fragment xml