In the previous article "Android Development Practice: The encapsulation of WiFi scanning function" describes how to use the Andriod API to achieve WiFi scanning, this article will focus on how to connect WiFi bar, here, also give a package of WiFi connection process class, Provides a simple interface for reuse in individual code projects.
Like a WiFi scan, a WiFi connection is also a time-consuming process, so it needs to be executed in a thread, notifying the caller of the connection result with a callback. The callback interface is defined as follows:
Public interface Wificonnectlistener {public void onwificonnectcompleted (Boolean isconnected);
From the Android WiFi setting can be seen, generally add a new WiFi connection, need to give three information, one is the SSID of WiFi, one is the password of WiFi, the other is the encryption type of WiFi, different encryption method, the configuration is different in the program when connected, Here you define an enumeration that gives four common types of encryption:
public enum SecurityMode { OPEN, WEP, WPA, WPA2}
Android WiFi connection process, generally divided into three steps, the first step, add network configuration, the second step, according to the network configuration connected WiFi, the third step, monitoring the system's WiFi connection status messages. The following is a straightforward example code, where the key points are commented in the code.
Package Com.example.testwifi; Import Java.util.list;import Java.util.concurrent.timeunit;import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.content.intentfilter;import Android.net.wifi.supplicantstate;import android.net.wifi.WifiConfiguration; Import Android.net.wifi.wifiinfo;import Android.net.wifi.WifiManager; public class Wificonnector { private static final int wifi_connect_timeout = 20; Time-out period for connecting WiFi p Rivate Context Mcontext; Private Wifimanager Mwifimanager; Private Lock MLock; Private Condition mcondition; Private Wificonncetreceiver Mwificonnectreceiver; Private Wificonnectlistener Mwificonnectlistener; Private Boolean misconnnected = false; private int mnetworkid =-1; Network encryption mode public enum SecurityMode {OPEN, WEP, WPA, WPA2}//notify the connection result of the listener interface public in Terface Wificonnectlistener {public void onwificonnectcompleted (Boolean isconnected); } public Wificonnector (context context, Wificonnectlistener listener) { Mcontext = context; MLock = NE W Reentrantlock (); Mcondition = Mlock.newcondition (); Mwifimanager= (Wifimanager) Mcontext.getsystemservice (context.wifi_seRvice); Mwificonnectreceiver = new Wificonncetreceiver (); Mwificonnectlistener = listener; } publi c Void Connect (final string SSID, final string password, final SecurityMode mode) { New Thread (New Runnable () { @Override public void Run () { If WiFi is not turned on, turn on WiFi if (!mwifimanager.iswifienabled ()) {mwifimanager.setwifienabled (true); } Register connection result Listener object Mcontext.registerreceiver (Mwificonnectreceiver, New Intentfilter (wifimanage r.supplicant_state_changed_action)); Connection Specifies the SSID if (!onconnect (Ssid,password,mode)) { Mwificonnectlistener.onwificonnectcompleted (FALSE); } else {mwificonnectlistener.onwificonnectcompleted (true); } Delete Registered Listener Class object Mcontext.unregisterreceiver (Mwificonnectreceiver); }}). Start (); } protected Boo Lean OnConnect (string SSID, string password, SecurityMode mode) { Add a new network configuration wificonfiguration cfg = new Wificonfigurati On (); Cfg. SSID = "\" "+ SSID +" \ "; if (password!=null &&! "". Equals (password)) {//Here is the key, if it is a WEP encryption network, the password needs to be placed in cfg.wepkeys[0] inside if (mode = = SECURITYMODE.WEP) { Cfg.wepkeys[0] = "\" "+ Password +" \ ""; Cfg.weptxkeyindex = 0; } else {cfg.presharedkey = "\" "+ Password +" \ ""; }} cfg.status = WifiConfiguration.Status.ENABLED; Add Network configuration Mnetworkid = Mwifimanager.addnetwork (CFG); Mlock.lock (); misconnnected = false; Connect the network if (!mwifimanager.enablenetwork (Mnetworkid, True)) {Mlock.unlock (); return false; } try { Wait for connection results mcondition.await (wifi_connect_timeout, timeunit.seconds); } catch (Interruptedexception e) {e.printstacktrace (); } mLock . Unlock (); return misconnnected; } WiFi connection message for monitoring system protected class Wificonncetreceiver ex Tends Broadcastreceiver { @Override public void OnReceive (context context, Intent Intent) { if (! WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals (Intent.getaction ())) {return; } Mlock.lock (); Wifiinfo info = Mwifimanager.getconnectioninfo (); if (Info.getnetworkid () ==mnetworkid && info.getsupplicantstate () = = supplicantstate.completed) {misconnnected = true; Mcondition.signalall (); } Mlock.unlock (); } }}
Similar to the package code for WiFi scanning, it also uses lock and condition, which is to block the result of waiting for the WiFi connection, to ensure the correct registerreceiver and unregisterreceiver network connection Status monitoring objects, at the same time, The WiFi connection timeout is set to prevent the interface from receiving a callback for a long time due to a problem with the WiFi module.
In addition, the Androidmanifest.xml file also remembers to add permission support OH:
<uses-permission android:name= "Android.permission.CHANGE_WIFI_STATE" ></uses-permission>< Uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE" ></uses-permission>< Uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE" ></uses-permission>
This WiFi connection class package to share here, I hope to be helpful to beginners, Java files See the attachment behind the post, there are any questions welcome message or letter [email protected] exchange.
This article is from the "Shadow Three People" blog, please be sure to keep this source http://ticktick.blog.51cto.com/823160/1410080