Android WIFI Analysis (i)

Source: Internet
Author: User

This article is based on an in-depth understanding of Android WiFi NFC and GPS volume and the Android N code combination analysis Wifiservice is the core service in frameworks, which is responsible for the WiFi function, mainly with the help of wpa_supplicant (referred to as Wpas) To manage and control the WiFi feature in the Android platform. The Wifiservice service will be analyzed by two lines: 1, Wifiservice creation and initialization; 2. Open the WiFi function, scan the network and connect the network in setting, and finally introduce Wifiwatchdogstatemachine and Captive Portal Check These two points of knowledge.creation and initialization of Wifiservice

Wifiservice is created in the Systemservice process, and Wifi related objects are defined:

/frameworks/base/services/java/com/android/server/systemserver.java

    Private Static Final String Wifi_service_class =            "Com.android.server.wifi.WifiService";     Private Static Final String Wifi_nan_service_class =            "Com.android.server.wifi.nan.WifiNanService";     Private Static Final String Wifi_p2p_service_class =            "Com.android.server.wifi.p2p.WifiP2pService";

The Systemservice class Process startup method run () calls the Startotherservice () method to create the Wifiservice process:

                if(Context.getpackagemanager (). Hassystemfeature (Packagemanager.feature_wifi_nan)) {Msystemservicema Nager.startservice (wifi_nan_service_class);//msystemservicemanager process Management object created in the Run () method}Else{slog.i (TAG,"No Wi-Fi nan Service (nan support not Present)");                } msystemservicemanager.startservice (Wifi_p2p_service_class);                Msystemservicemanager.startservice (Wifi_service_class); Msystemservicemanager.startservice ("Com.android.server.wifi.scanner.WifiScanningService"); if(!Disablertt) {Msystemservicemanager.startservice ("Com.android.server.wifi.RttService"); }

The study of Systemservice can be referred to "in-depth understanding of Android: Volume II", chapter 3rd

Wifiservice inherits Systemservice, the package name Com.android.service.wifi, whose constructors initialize a Wifiserviceimpl object:

 Public Final class extends Systemservice {    privatestaticfinal String TAG = "Wifiservice";     Final Wifiserviceimpl Mimpl;      Public Wifiservice (Context context) {        Super(context);         New Wifiserviceimpl (context);}    }

Here, we first introduce two points of knowledge, namely HSM (Hierarchical state machine, structured states machines) and Asyncchannel.

Introduction to HSM and Asyncchannel

The HSM (the corresponding class is StateMachine) and Asyncchannel are two important classes in the Android Framework.

The state-level relationship in the HSM is similar to the derivation and inheritance of parent-child classes in Java, that is, implementing generic functionality in the parent state and implementing some specific processing in the sub-state, but unlike the class derivation in Java, the parent-child state in the HSM corresponds to two classes that have no derivation. You need to create two objects when you use them.

The Asyncchannel is used for communication between two handler, and the specific means of communication for the source handler is to send the message to the destination handler through SendMessage, while the destination handler Replytomessage Processing of the results; The two handler can be in the same process or belong to two different processes.

1. Use of HSM

Addstate (): Adds a state. You can also specify a parent state

Transitionto (): Switch state machine to a State

Obtainmessage (): The HSM is built around a handler, and the outside world can only invoke the HSM's Obtainmessage () to get a message

SendMessage (): Sends a message to the HSM. Handler in the HSM will handle it

Defermessage (): Retains a message that is left in the next new state for processing

Start (): Start state machine

Quit (), Quitnow (): Stop state machine

The hierarchical relationship of state and state directly in the HSM is reflected in:

1) After SM starts, the initial state of the EA will be executed in the derived order, that is, its ancestor state executes first, the child state executes after

2) When the state sends a switch, the exit of the old state is executed first, the new state's enter is executed, and the corresponding state on the new and old state derivation tree needs to execute the exit or enter function. Similar to C + + class construction/destructor execution order

3) When the state handles a message, if the child status cannot be processed (return not_handled), it is handed to the parent state to process

2, the use of Asyncchannel

1) in a simple request/response mode, the Server side does not need to maintain the client's information, it just handles requests from the client.

Client calls Connectsync (synchronous connection) or connect (asynchronous connection, client receives cmd_channel_half_connected message after successful connection) to connect to server.

2) In contrast to the Request/response mode, the server side maintains client information.

The Server can send its own state or some other meaningful information to the client. WPA_CLI and Wpa_supplicant are applications of this pattern, WPA_CLI can send commands to Wpas to execute, and Wpas will also notify WPA_CLI of its status and some other information.

An example of the use of Asyncchannel in the 2nd application pattern is presented in an asynchronous way:

1) client calls Asyncchannel's Connect () function, and the client's handler receives a message named cmd_channel_half_connected;

2) When the Client processes cmd_channel_half_connected messages, a message called Cmd_channel_full_connection is sent to the server via the SendMessage () function;

3) Server side handler will receive this cmd_channel_full_connection message, after successfully processing it, the server first calls Asyncchannel's connected () function, and then through the SendMessage () function to send cmd_channel_fully_connected messages to client side;

4) Client side receives cmd_channel_fully_connected message. At this point, the client and server side successfully establish the connection.

5) The Clinet and server side two handler can use SendMessage () and Replytomessage () to complete the request message and reply message delivery. Note that only the Server side needs to call Replytomessage () for those situations that require a reply.

6) The Disconnect () function can be called at either end of the Client and server to end the connection. This function will cause both client and server to receive cmd_channel_disconnected messages.

Note this part of the process describes the comments from the Asyncchannel.java file, but in the actual 3rd step, Asyncchannel is typically created by the client and cannot be obtained by the server. The next step is to demonstrate the correct approach through code.

The Getchannel () function of the Wifimanager class creates a asyncchannel to establish a connection relationship with Servicehandler in Wifiservice and returns the Asyncchannel object:

    Private synchronizedAsyncchannel Getchannel () {if(Masyncchannel = =NULL) {Messenger Messenger=Getwifiservicemessenger ();//is the server side of handler on the client side of the Representativeif(Messenger = =NULL) {                Throw NewIllegalStateException ("Getwifiservicemessenger () returned null! This is invalid. "); } Masyncchannel=NewAsyncchannel ();//asyncchannel is typically created on the client side mconnected=NewCountdownlatch (1); Servicehandler is a wifimanager-defined inner class Handler Handler Handler=NewServicehandler (mlooper);//client handler Masyncchannel.connect (Mcontext, Handler, messenger);//mcontex T is the client side of the context objectTry{mconnected.await (); } Catch(interruptedexception e) {log.e (TAG,"Interrupted wait at Init"); }        }        returnMasyncchannel; }

Getwifiservicemessager () function, gets the handler reference of the Wifiservice end for the client to establish Asyncchannel communication with Wifiservice:

     Public Messenger Getwifiservicemessenger () {        try  {            return  Mservice.getwifiservicemessenger (); The returned Messenger object contains the Wifiservice handler        catch  (RemoteException e) {            throw  e.rethrowfromsystemserver ();        }    }

Mservice is a Iwifimanager class object, which is essentially a aidl interface, Wifiserviceimpl class inherits from Iwifimanager.stub, so Getwifiservicemessenger () The implementation of the function is in Wifiserviceimpl.java:

    /**      * Get a reference to handler. This was used by a client to establish     * An asyncchannel communication with Wifiservice     */    PU Blic  Messenger Getwifiservicemessenger () {        enforceaccesspermission ();//Permission Check        Enforcechangepermission ();         return New Messenger (Mclienthandler);//The target is encapsulated by Messenger handler    }

The Connect () function triggers a client-side handler (that is, Servicehandler) to receive a cmd_channel_half_connected message, which is handled by Wifimanager Servicehandler:

        Private voiddispatchmessagetolisteners (Message message) {Object Listener=RemoveListener (MESSAGE.ARG2); Switch(message.what) { Caseasyncchannel.cmd_channel_half_connected:if(Message.arg1 = =asyncchannel.status_successful) {//half connection succeeded Masyncchannel.sendmessage (asyncchannel.cmd_channel_full_connection);//Send Cmd_cha to server side Nnel_full_connection}Else{log.e (TAG,"Failed to set up channel connection"); //This would cause all further async API calls on the Wifimanager//To- fail and throw an exceptionMasyncchannel =NULL;                    } mconnected.countdown ();  Break;
                 Caseasyncchannel.cmd_channel_fully_connected://Successful connection//Ignore                     Break;  Caseasyncchannel.cmd_channel_disconnected://Connect off LOG.E (TAG,"Channel connection Lost"); //This would cause all further async API calls on the Wifimanager//To- fail and throw an exceptionMasyncchannel =NULL; Getlooper (). Quit (); Connection close, exit thread Break;

Define ClientHandler in Wifiserviceimpl.java to handle messages sent by client side:

    /*** Handles client connections processing Client connection*/    Private classClientHandlerextendsHandler {@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { Caseasyncchannel.cmd_channel_half_connected: {
Handling cmd_channel_half_connected messages received due to ac.connect calls
The message carries a Asyncchannel object, the AC
if(Msg.arg1 = =asyncchannel.status_successful) { if(DBG) SLOG.D (TAG, "New client listening to asynchronous messages"); //We Track the clients by the Messenger//since it is expected to being always availablemtrafficpoller.addclient (Msg.replyto);//wifitrafficpoller class
                    }  Break; }                 Caseasyncchannel.cmd_channel_disconnected: {if(Msg.arg1 = =asyncchannel.status_send_unsuccessful) {                        if(DBG) SLOG.D (TAG, "Send failed, client connection lost"); } Else {                        if(DBG) SLOG.D (TAG, "Client connection lost with reason:" +msg.arg1);                    } mtrafficpoller.removeclient (Msg.replyto);  Break; }                 Caseasyncchannel.cmd_channel_full_connection: {//server End receives this message first Asyncchannel AC=NewAsyncchannel ();//Create a new Asyncchannel object, call its connect () function Ac.connect (Mcontext, This, Msg.replyto); Msg.replyto represents the client side of the handler, that is, Wifimanager Servicehandler
The Connect () function will trigger the cmd_channel_half_connected message to be sent, and the message will carry the corresponding Asyncchannel object, which is the AC
Break; }

The Addclient () method of the Wifitrafficpoller class:

    void addclient (Messenger client) {        Message.obtain (Mtraffichandler, add_client, client). Sendtotarget ();    

Add_client messages are handled by the class's inner class Traffichandler:

                 Case add_client:                    mclients.add (Messenger) msg.obj);//Save the above Asyncchannel object for sending messages to the CLIENT
break;

Since the server side cannot get the client-side Asyncchannel object, a new Asyncchannel is created and connect to the client side.

Analysis of Wifiservice structure function

As seen above, the Wifiservice constructor primarily creates a Wifiserviceimpl object, so focus on the Wifiserviceimpl constructor:

     PublicWifiserviceimpl (Context context) {Handlerthread Wifithread=NewHandlerthread ("Wifiservice");        Wifithread.start (); Handlerthread Wifistatemachinethread=NewHandlerthread ("Wifistatemachine");        Wifistatemachinethread.start (); Mwifistatemachine=Newwifistatemachine (Mcontext, Mfacade, Wifistatemachinethread.getlooper (), Musermanager, MWifiInjector, Newbackupmanagerproxy (), Mcountrycode); Create a Wifistatemachine object Mwifistatemachine.enablerssipolling (true); RSSI (signal reception strength) polling mechanism
Wpas supported RSSI information includes: Receive signal strength, connection speed, noise intensity (noise), and frequency Mclienthandler
=NewClientHandler (Wifithread.getlooper ());//For Asyncchannel, with interactive objects from Wifimanager Mwifistatemachinehandler=NewWifistatemachinehandler (Wifithread.getlooper ());//For Asyncchannel, whose interaction object is from Wifistatemachine}

Android WIFI Analysis (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.