Android4.4.2 source analysis of WiFi module (i)

Source: Internet
Author: User

By the androidsetting source analysis of the WiFi module interface fragment for Wifisettings.java, about the setting module source code analysis can refer to

analysis of the source code of Android System (i)---Settings


Have written a few about the Android source code, the source codes are too large, so if you want to analyze a module may not know how to start, say a thought
1, the analysis of the source of English reading ability to be enough, want to analyze a module generally find the module corresponding to the English, is the module
2, find the manifest configuration file androidmani.fest First, find the program main interface activity
3, you can see what the app is all about by looking at the permissions in the configuration file
Roughly through the above three steps to enter the source code for analysis

For WiFi, we can know through the manifest file, need the following several permissions, the meaning of the following comments
<!--allows the program to get WIFI status--    <uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE"/>    <!--allow program to change WIFI status--    <uses-permission android:name= "Android.permission.CHANGE_WIFI_STATE"/>    <!--allows the program to get mobile network status--    <uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>    <!--allows programs to change network status--    <uses-permission android:name= "Android.permission.CHANGE_NETWORK_STATE"/ >    <!--allow programs to access the network--    <uses-permission android:name= "Android.permission.INTERNET"/>

If you use as a development tool in the use of WiFi if you do not have the right to warn you, the feeling is still very human, if all the warnings are resolved as the program should be very few unexpected bugs, and as the single-step debugging can be very good to find bugs, beautiful interface, Could not help but strongly recommend.
Because it is the first time to contact WiFi source code, I will be in order to analyze, of course, this may be a bit messy, complete analysis will then follow the function point analysis, but have to wait until the next blog. Well, gossip less, formally into the WiFi source analysis,




1,wifisettings belongs to fragment, realizes the dialog box's Click event interface, the code is as follows
public class Wifisettings extends Restrictedsettingsfragment        

In the Oncreateview method, first determine whether the application is first run, and set a different layout based on whether it is the first time
1>,if (Msetupwizardmode) loads the start layout
View view = Inflater.inflate (R.layout.setup_preference, container, false);

otherwise load normal layout
View v = inflater.inflate (r.layout.add_preference_list_fragment,null);

then the Onactivitycreated method
2>
mp2psupported = Getpackagemanager (). Hassystemfeature (Packagemanager.feature_wifi_direct);

This code is used to determine if the WiFi direct connection is supported: if the device supports Wi-Fi direct networking or not
WiFi direct meaning is said: The device can be directly through the WiFi sharing files, pictures and so on, similar to Bluetooth transmission, to achieve point-to-point connection, communication (requires two devices must be located in the same network segment). Can see whether the device supports WiFi direct connection via Packagemanager hassystemfeature
Directory is /android/external/robolectric/src/main/java/com/xtremelabs/robolectric/res/
public boolean hassystemfeature (String name) {return Systemfeaturelist.containskey (name)? Systemfeaturelist.get (Name ): false;   }

It is known from the source that the method iterates through the Systemfeaturelist list and determines whether the incoming feature is included, through Readpermissionsfromxml (File f) in Packagemanagerservice Incoming XML file parsing gets the permission supported by the device

3>, next get to WiFi Management class object Mwifimanager, used to turn WiFi on/off, scan WiFi, connect WiFi, etc.
Mwifimanager = (Wifimanager) getsystemservice (Context.wifi_service);

4> The preference list is displayed differently by getting the value to set_wifi_priority

<pre name= "code" class= "Java" >if (Getresources (). Getboolean (r.bool.set_wifi_priority)) {            Addpreferencesfromresource (r.xml.wifi_sort_settings);            Mdefaulttrustap                    = (preferencecategory) findpreference ("default_trust_access_points");            Mconfigedap = (preferencecategory) findpreference ("configed_access_points");            Munknownap = (preferencecategory) findpreference ("unknown_access_points");        }        else {            addpreferencesfromresource (r.xml.wifi_settings);        }
for Boolean value "Set_wifi_priority", you can view the Z:\L7-A1\android\packages\apps\Settings\res\values\bools.xml fileThis value indicates that the whether to show hotspot via the AP's classification access point priority setting is to display the WiFi list according to the WiFi priority that is being searched, There are three types of levels to see: Default Trust access point, trusted access point, unknown access pointbecause here the Boolean value is set to False, so do not sort by priority 5>, the next step is to add the WiFi switch, as for the code in the navigation bar actionbar add switch code similar to Bluetooth, do not repeat here, you can see, The bluetooth switch switches into the Wifienabler, so the switch management for WiFi is located in Wifienablerswitch
Mwifienabler = new Wifienabler (activity, actionbarswitch);

Enter Wifienabler can see, the class did two things, the first registered radio monitor WiFi changes and then change the status of switch, the second to add click-Listen Event
The broadcasts are listening to events that have
When the WIFI status changes, the broadcast mintentfilter = new Intentfilter (wifimanager.wifi_state_changed_action) is sent;         The Order matters! We really should not depend on this. :(        mintentfilter.addaction (wifimanager.supplicant_state_changed_action);       The broadcast mintentfilter.addaction (wifimanager.network_state_changed_action) is sent when the device network status changes;

The action wifimanager.supplicant_state_changd_action is defined as follows, indicating that the status of the connection being created has changed, and that a new connection is available to obtain a specific connection state to the WiFi, This broadcast is useless if you are only interested in the overall state of the connection
/**     * Broadcast Intent action indicating the state of establishing a connection to * An access point have     Chan Ged. One extra provides the new     * {@link supplicantstate}. Note that the supplicant is a Wi-Fi specific, and is not a generally the most     useful thing- UST interested in     * The overall state of connectivity.     * @see #EXTRA_NEW_STATE     * @see #EXTRA_SUPPLICANT_ERROR * *    @SdkConstant (sdkconstanttype.broadcast_ intent_action) public    static final String supplicant_state_changed_action =        " Android.net.wifi.supplicant.STATE_CHANGE ";


Next, we'll watch the broadcast.
Private final Broadcastreceiver mreceiver = new Broadcastreceiver () {@Override public void onreceive (Contex            T context, Intent Intent) {String action = intent.getaction (); if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals (ACTION)) {//wifi state changes to update the state of switch, WIFI status exists in Wifimanager. Extra_wifi_state  handlewifistatechanged (Intent.getintextra (wifimanager.extra_w              Ifi_state, Wifimanager.wifi_state_unknown)); The Needprompt method is used to determine if airplane mode and flight mode are invalid  if (wifisettings.needprompt (context)) {Setswitchche                Cked (FALSE); }} else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals (ACTION)) {//The connection changes when the update is Wifimanager. Extra_new_state storage changed State  if (!mconnected.get ()) {handlestatechanged (wifiinfo.getdetail Edstateof (supplicantstate) Intent.getparcelableextra (wifimanager.ext(ra_new_state))); }} else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals (ACTION)) {//update &NBS when the network state changes P                Networkinfo info = (networkinfo) Intent.getparcelableextra (wifimanager.extra_network_info);                Mconnected.set (info.isconnected ());            Handlestatechanged (Info.getdetailedstate ()); }        }    };

When the WiFi switch status changes when the update put AH as follows:
private void handlewifistatechanged (int state) {        switch (state) {case            wifimanager.wifi_state_enabling:// Opening WiFi             mswitch.setenabled (false);                break;            Case Wifimanager.wifi_state_enabled://wifi has opened                setswitchchecked (true);                Mswitch.setenabled (true);                break;            Case wifimanager.wifi_state_disabling://is shutting down WIFI                mswitch.setenabled (false);                break;            Case Wifimanager.wifi_state_disabled://wifi has closed                setswitchchecked (false);                Mswitch.setenabled (true);                break;            Default:                setswitchchecked (false);                Mswitch.setenabled (true);                break;        }    }

You can see that the method has been commented out for the Update method when the network state changes, because there is no need to update the subtitle of preference

  private void Handlestatechanged (@SuppressWarnings ("unused") Networkinfo.detailedstate state) {        //after the Refactoring from a checkboxpreference to a Switch, this method is useless since        //There are nowhere to display a summa Ry.        This code was kept in case a re-introduces a associated text.        /*//Wifiinfo is valid if and only if Wi-Fi is enabled.        Here we use the state of the the switch as an optimization.        if (state! = null && mswitch.ischecked ()) {            Wifiinfo info = mwifimanager.getconnectioninfo ();            if (info! = null) {                //setsummary (Summary.get (Mcontext, Info.getssid (), State));}        }        */    }

the Listener code for the switch's click event is as follows
public void OnCheckedChanged (Compoundbutton buttonview, Boolean isChecked) {//do Nothing if called as a result of        A state machine event if (mstatemachineevent) {return; } if (Mcontext.getresources (). Getboolean (R.bool.wifi_to_cell)) {Connectivitymanager Mconnservice = (Con                    Nectivitymanager) Mcontext.            Getsystemservice (Context.connectivity_service); if (mconnservice! = null) {Networkinfo NetInfo = (networkinfo) mconnservice. getnet                Workinfo (Connectivitymanager.type_wifi); if (netInfo! = null && netinfo.isconnected ()) {Settings.System.putInt (Mcontext.getcontentresol                Ver (), wifi_is_connected, CONNECTED);                            } else {Settings.System.putInt (Mcontext.getcontentresolver (), wifi_is_connected,                disconnected);        }            }        }Show Toast Message If Wi-Fi is not allowed in airplane mode//To determine if WiFi is disallowed in airplane mode  if (isChecked && (Wifisettings.needprompt (mcontext) | |! Wirelesssettings.isradioallowed (Mcontext, Settings.Global.RADIO_WIFI))) {Toast.maketex            T (Mcontext, R.string.wifi_in_airplane_mode, Toast.length_short). Show (); Reset switch to OFF.            No Infinite Check/listenenr loop.            Buttonview.setchecked (FALSE);        Return        }//Disable tethering if enabling Wifi int wifiapstate = Mwifimanager.getwifiapstate ();                if (isChecked && (wifiapstate = = wifimanager.wifi_ap_state_enabling) | | (wifiapstate = = wifimanager.wifi_ap_state_enabled)))        {mwifimanager.setwifiapenabled (null, FALSE);        }//shouldn ' t setwifienabled (true) in airplane mode.           if (isChecked && wifisettings.needprompt (mcontext)) { Return } else {//setwifienabled turns wifi on or off, it sends a broadcast with a WiFi status change: Wifi_state_changed_action  if (mwifimanager.se  Twifienabled (isChecked)) {//Intent have been taken into account, disable until new state//            is active mswitch.setenabled (false); } else {//Error Toast.maketext (Mcontext, R.string.wifi_error, Toast .            Length_short). Show (); }}}<span style= "FONT-SIZE:14PX;" ></span>
for the value of the mstatemachineevent is assigned when the switch is set, the role of switching protection, to ensure that when the switch is clicked to set the switch status successfully before entering the Click event Method
private void Setswitchchecked (Boolean checked) {        if (checked! = mswitch.ischecked ()) {            Mstatemachineevent = True ;            mswitch.setchecked (checked);            Mstatemachineevent = false;        }    }

the way to turn WIFI on or off is, mwifimanager.setwifienabled (Boolean enable), which sends a broadcast wifimanager.wifi_state_changed_action when it is opened, Can listen to the broadcast to change the UI
Android4.4.2 Source analysis of the WiFi module (ii)


Android4.4.2 source analysis of WiFi module (i)

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.