Android code connected to WiFi when the system switched to other WiFi issues

Source: Internet
Author: User

First of all, the Android code connected to WiFi a few steps : (The following refers to the specific API function self-examination ha, write the time by virtue of the impression of roughly written down)


Reprint please specify the source:

Fat Tiger : HTTP://BLOG.CSDN.NET/LJPHHJ


1. First to turn on the wifi connection switch, mwifimanager.setwifienabled (TRUE)


2. Geta list of WiFi connections by getting List<scanresult >. (Mwifimanager. getscanresults)


3. Get the list<wificonfiguration> list. (Mwifimanager. getconfigurednetworks)


4. (1) Create a configuration to connect to the Wificonfiguration (including encryption, SSID, password, [priority]<-This is the key point of this blog post) "If this is the way to proceed, the 5th step" or (2) You connect the 3rd step to get a networkid in the WiFi configuration list. (Skip straight to step 6th)


5.mConnectNetworkId = Mwifimanager.addnetwork (wificonfiguration), add this configuration to WiFi Config (actually that file path:/data/misc/ wifi/wpa_supplicant.conf [PS: This file is a bunch of online "View WiFi password Artifact" Foundation, including the Universal WiFi key Oh!])


6.mwifimanager.enablenetwork (NetId, true);


7. Then this way you need to wait for the WiFi connection (two ways, one with radio, one is polling, your choice)


Go to the Chase:


There are problems ( I also ask others to know, some places may not be accurate, if the great god see this blog, can be supplemented or corrected, thank you ):


Android 4.0 after the roaming mechanism, Android 5.0 added another mechanism:auto join mechanism, two mechanisms roughly the same, that is, when there is an SSID signal strength, encryption method, Or the other factor calculates a value (that is, the concept of priority in the configuration file) is higher than the priority value of the WiFi you want to connect to, try to connect to the higher priority of the Wi-Fi.


Learn about this problem and see what we're going to encounter when connecting to a WiFi (Android Version >= 4.0)




Personal comparison like to use the figure to explain, write a blog casually draw a picture, easy for everyone to understand.

, you can probably know that the cause of this problem is mainly: The priority list, this thing in our WiFi disconnected with an SSID connection, the system read a priority connection to determine a connection to the SSID, and we just want to connect our SSID, This is equivalent to two threads at the same time in progress, one but our SSID first connected, the system of the connection later we step on the connection, it will cause the SSID we just connected, immediately disconnected.


Some netizens will be smart. The SSID to be connected its wificonfiguration has a high priority configuration (highest: 100000), ensuring that it becomes the highest profile priority. In this case, the SSID will be recognized by the system, connected to the SSID we connected first, but in fact this place, you can not guarantee that you write the priority in the system when the priority list in the configuration file is removed. )


Finally, my personal solution is to use the same way as the System Setup module to connect to WiFi (that is, call connect to connect to WiFi, there is time to look at this piece of code, Wifisettings.java in the Submit method inside is the connection logic, the Connect method is also there, I personally think it should be a queue similar, so that you connect the operation and the operation of the system connection should have a succession relationship, and the Connect method will update the priority "The WiFi priority on the last connection is higher", so the SSID we want to connect to gets the highest priority)


Solution: The API that reflects the system settings connection (@hide)

/** * By reflecting different versions of the Connect method to connect to WiFi * * @author jiangping.li * @param netId * @return * @since MT 1.        0 * */private Method connectwifibyreflectmethod (int netId) {method connectmethod = null; if (Build.VERSION.SDK_INT >= build.version_codes.            JELLY_BEAN_MR1) {logger.i (TAG, "Connectwifibyreflectmethod Road 1"); Reflection method: Connect (int, listener), 4.2 <= phone ' s Android version for (method MethodSub:mWifiManager.getCla                    SS (). Getdeclaredmethods ()) {if ("Connect". Equalsignorecase (Methodsub.getname ())) {                    class<?>[] types = Methodsub.getparametertypes ();  if (types! = null && types.length > 0) {if ("int". Equalsignorecase (Types[0].getname ()))                        {Connectmethod = methodsub; }}} if (Connectmethod ! = null) {try {Connectmethod.invoke (mwifimanager, netId, NULL);                    } catch (Exception e) {e.printstacktrace ();                    LOGGER.I (TAG, "Connectwifibyreflectmethod Android" + Build.VERSION.SDK_INT + "error!");                return null; }}} and Else if (Build.VERSION.SDK_INT = = Build.version_codes. Jelly_bean) {//Reflection method: Connect (Channel C, int networkid, ActionListener Listener)//temporarily do not handle 4.1 cases, 4        .1 = = Phone ' s Android version logger.i (TAG, "Connectwifibyreflectmethod Road 2"); } else if (Build.VERSION.SDK_INT >= build.version_codes. Ice_cream_sandwich && Build.VERSION.SDK_INT < Build.version_codes.            Jelly_bean) {logger.i (TAG, "Connectwifibyreflectmethod Road 3");  Reflection method: Connectnetwork (int networkid),//4.0 <= phone ' s Android version < 4.1          For (Method MethodSub:mWifiManager.getClass (). Getdeclaredmethods ()) {if (" Connectnetwork ". Equalsignorecase (Methodsub.getname ())) {class<?>[] types = Methodsub.getparamete                    Rtypes ();  if (types! = null && types.length > 0) {if ("int". Equalsignorecase (Types[0].getname ()))                        {Connectmethod = methodsub;                    }}}} if (Connectmethod! = null) {try {                Connectmethod.invoke (Mwifimanager, netId);                    } catch (Exception e) {e.printstacktrace ();                    LOGGER.I (TAG, "Connectwifibyreflectmethod Android" + Build.VERSION.SDK_INT + "error!");                return null;  }}} else {//< Android 4.0 return null;      } return Connectmethod; }

Method Connectmethod = Connectwifibyreflectmethod (netId);        if (Connectmethod = = null) {            logger.i (TAG,                    "Connect WiFi by Enablenetwork method, Add by Jiangping.li");            Generic API            Mwifimanager.enablenetwork (NetId, True);        }




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android code connected to WiFi when the system switched to other WiFi issues

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.