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
- Add instances to actionbar
- Pass the switch instance to the Bluetooth Enabler instance by constructive method
- Call the method of adding menu in fragment
-
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
- Display to screen
- Constructing an instance of Bluetooth Discoverable Enabler to display and update the subtitle summary of mMyDevice Preference
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
- Pop-up dialog box for Bluetooth renaming operation
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.
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.
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.
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
-
Add the list of pairable devices mPaired Devices Category
- Call the following method to pass the list of pairable devices to DeviceList Preference Fragment for management
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
- 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.
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.
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>, 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.
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.
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
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
- 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:
The code added or removed by preferences creen is as follows:
- 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
4>, initDevicePreference() method to get the matched Bluetooth device and set up the listening event
5>, onDevicePreferenceClick() method, click events for remote Bluetooth devices
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.
Next, the Bluetooth switch state is set in resume().
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
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.
Next, let's look at how to change the local Bluetooth adapter
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
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
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
The way to update the subtitle is as follows, because there are three modes, so there are also three situations for the subtitle.
Then add a click event to preference, reverse the flag when clicking preference, and update the summary of preference and Bluetooth scanning mode.
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.
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
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
The addCachedDevices() code is as follows
The onDeviceAdded(cachedDevice) code is as follows
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
When the cache list is filtered, the createDevicePreference(cachedDevice) method is called to load it if it meets the criteria.
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.
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.
When remote devices are found during scanning, the following processing is performed
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.
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.
Next, take a look at the code for the connectWithoutResettingTimer(connectAllProfiles) method
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