Android WiFi usage Record

Source: Internet
Author: User
Tags sendmsg

Recently in the development of the WiFi part of doing Android, the connected tool class referenced the tool class of this article.

Http://www.cnblogs.com/zhuqiang/p/3566686.html

Some of the problems encountered in development, where some of the solutions have been documented.

1. Identification of WiFi encryption mode

String capabilities = scanresult.capabilities;
if (Capabilities.contains ("WPA") | | | capabilities.contains ("WPA")) {
((wifiholder) holder). SetType (WifiConnector.WifiCipherType.WIFICIPHER_WPA);
} else if (Capabilities.contains ("WEP") | | | capabilities.contains ("WEP")) {
((wifiholder) holder). SetType (WifiConnector.WifiCipherType.WIFICIPHER_WEP);
} else {
((wifiholder) holder). SetType (WifiConnector.WifiCipherType.WIFICIPHER_NOPASS);
}

Determine how WiFi is encrypted by getting Scanresult's capabilities


2. Success rate of WiFi connection

Development found when I entered the correct password, I was not able to connect to my designated WiFi. The reason for this is that the Wifimanager will save the history of the WiFi configuration caused by the impact.

Public list<wificonfiguration> Cleanwificonfigurednetworks (String SSID) {
list<wificonfiguration> Configurednetworks = Wifimanager
. Getconfigurednetworks ();

for (int i = 0; i < configurednetworks.size (); i++) {
Wifimanager.removenetwork (Configurednetworks.get (i). Networkid);
}
return configurednetworks;
}
It is simple to simply empty the history configuration or set other to be unavailable.

3.wifi Connection Successful Monitoring

Do not like radio monitoring, a lot of problems, I directly to the current connection WiFi information to judge.

Get the current connection WiFi information via Wifimanager.getconnectioninfo (),

Connectioninfo.getssid (). Contains (SSID) | |
Connectioninfo.getsupplicantstate ()! = supplicantstate.completed

Again determine the SSID of WiFi and the status of Wifimanager, both conditions are satisfied when the WiFi connection is successful.
Project requirements I'm going to do this next. Socket communication, in which the IP address obtained in the presence of delay increases the new conditional judgment, for the Meteredhint parameter in Wifiinfo additional judgment. When this becomes true
, the correct IP is obtained. This parameter gets the method to hide, which cannot be called with reflection to successfully use the code as follows:

Calling the Hide method from the reflection method
public boolean getwifiinfohint (Wifiinfo connectioninfo) throws Instantiationexception {
Class AClass = Connectioninfo.getclass ();
try {
Method getmeteredhint = Aclass.getdeclaredmethod ("Getmeteredhint");
Getmeteredhint.setaccessible (TRUE);
Object invoke = Getmeteredhint.invoke (ConnectionInfo);
Return (Boolean) invoke;
} catch (Nosuchmethodexception e) {
E.printstacktrace ();
} catch (Illegalaccessexception e) {
E.printstacktrace ();
} catch (InvocationTargetException e) {
E.printstacktrace ();
}
return false;
}

Get the IP address method for the server:
Dhcpinfo info = Wifimanage.getdhcpinfo ();
String serveraddress = Inttoip (info.serveraddress);

Convert the acquired int to a real IP address, refer to the online, modify the next
Private String Inttoip (int i) {
Return (I & 0xFF) + "." + (((I >> 8) & 0xFF) + "." + ((I >> +) & 0xFF) + "." + ((i >>) &A mp 0xFF);
}



OK to end all the changes after the code is as follows:

Package com.dopool.usersystem.hotspot;


Import Android.content.Context;
Import Android.net.wifi.ScanResult;
Import Android.net.wifi.SupplicantState;
Import android.net.wifi.WifiConfiguration;
Import Android.net.wifi.WifiConfiguration.AuthAlgorithm;
Import Android.net.wifi.WifiConfiguration.KeyMgmt;
Import Android.net.wifi.WifiInfo;
Import Android.net.wifi.WifiManager;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.text.TextUtils;
Import Android.util.Log;

Import com.dopool.usersystem.Constant;
Import COM.ZHY.HTTP.OKHTTP.UTILS.L;

Import Java.lang.reflect.Field;
Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;
Import java.util.ArrayList;
Import java.util.List;

public class Wificonnector {
Public Handler Mhandler;
Wifimanager Wifimanager;

/**
* Send messages to UI
*
* @param info message
*/
public void sendmsg (String info) {
if (Mhandler! = null) {
Message msg = new Message ();
Msg.obj = info;
Mhandler.sendmessage (msg);//Send Message to Handler
} else {
LOG.E ("WiFi", info);
}
}

WIFICIPHER_WEP is WEP, WIFICIPHER_WPA is wpa,wificipher_nopass no password
public enum Wificiphertype {
WIFICIPHER_WEP, WIFICIPHER_WPA, Wificipher_nopass, Wificipher_invalid
}

constructor function
Public Wificonnector (Context context) {
Get Wifimanager Object
This.wifimanager = (Wifimanager) context.getsystemservice (Context.wifi_service);
}

Provides an external interface for incoming wireless networks to be connected
public void Connect (string SSID, string password, Wificiphertype type) {
Thread thread = new Thread (new connectrunnable (SSID, password, type));
Thread.Start ();
}

See if you have previously configured this network
Private Wificonfiguration isexsits (String SSID) {
list<wificonfiguration> Existingconfigs = Wifimanager
. Getconfigurednetworks ();
for (Wificonfiguration existingconfig:existingconfigs) {
if (existingConfig.SSID.equals ("\" + SSID + "\")) {
return existingconfig;
}
}
return null;
}


Private Wificonfiguration Createwifiinfo (string SSID, String Password,
Wificiphertype Type) {
wificonfiguration config = new wificonfiguration ();
Config.allowedAuthAlgorithms.clear ();
Config.allowedGroupCiphers.clear ();
Config.allowedKeyManagement.clear ();
Config.allowedPairwiseCiphers.clear ();
Config.allowedProtocols.clear ();
Config. SSID = "\" "+ SSID +" \ ";
NoPass
if (Type = = Wificiphertype.wificipher_nopass) {
Config.allowedKeyManagement.set (Keymgmt.none);
}
Wep
if (Type = = Wificiphertype.wificipher_wep) {
if (! Textutils.isempty (Password)) {
if (Ishexwepkey (Password)) {
Config.wepkeys[0] = Password;
} else {
Config.wepkeys[0] = "\" "+ Password +" \ "";
}
}
Config.allowedAuthAlgorithms.set (Authalgorithm.open);
Config.allowedAuthAlgorithms.set (authalgorithm.shared);
Config.allowedKeyManagement.set (Keymgmt.none);
Config.weptxkeyindex = 0;
}
Wpa
if (Type = = WIFICIPHERTYPE.WIFICIPHER_WPA) {
Config.presharedkey = "\" "+ Password +" \ "";
Config.hiddenssid = true;
Config.allowedauthalgorithms
. Set (Authalgorithm.open);
Config.allowedGroupCiphers.set (WifiConfiguration.GroupCipher.TKIP);
Config.allowedKeyManagement.set (KEYMGMT.WPA_PSK);
Config.allowedpairwiseciphers
. Set (WifiConfiguration.PairwiseCipher.TKIP);
You need to modify this here or you cannot automatically re-link
Config.allowedProtocols.set (WifiConfiguration.Protocol.WPA);
Config.allowedGroupCiphers.set (WifiConfiguration.GroupCipher.CCMP);
Config.allowedpairwiseciphers
. Set (WifiConfiguration.PairwiseCipher.CCMP);
Config.status = WifiConfiguration.Status.ENABLED;
}
return config;
}

Turn on the WiFi feature
Private Boolean Openwifi () {
Boolean bRet = true;
if (!wifimanager.iswifienabled ()) {
BRet = Wifimanager.setwifienabled (true);
}
return bRet;
}

Private Boolean Closeifi () {
Boolean bRet = true;
if (wifimanager.iswifienabled ()) {
BRet = wifimanager.setwifienabled (false);
}
return bRet;
}


Class Connectrunnable implements Runnable {
Private String SSID;

private String password;

Private Wificiphertype type;

Public connectrunnable (String SSID, string password, Wificiphertype type) {
This.ssid = SSID;
This.password = password;
This.type = type;
}

@Override
public void Run () {
try {
Open wifi
Openwifi ();
Sendmsg ("opened");
Thread.Sleep (200);
It takes a while to turn on the WiFi function (I usually need about 1-3 seconds to test on my phone), so wait until WiFi
The following statement can be executed when the state becomes wifi_state_enabled
while (wifimanager.getwifistate () = = wifimanager.wifi_state_enabling) {
try {
To avoid a program that has been in a while loop, let it sleep for 100 milliseconds to detect ...
Thread.Sleep (100);
} catch (Interruptedexception IE) {
}
}

Remove the previous WiFi configuration
list<wificonfiguration> Saveconfigurenetworks = Cleanwificonfigurednetworks (SSID);

Wificonfiguration wificonfig = createwifiinfo (SSID, password,
Type);

if (Wificonfig = = null) {
Sendmsg ("Wificonfig is null!");
Return
}

int NetID = Wifimanager.addnetwork (wificonfig);
Boolean enabled = Wifimanager.enablenetwork (NetID, true);
Boolean connected = Wifimanager.reconnect ();

Wifiinfo ConnectionInfo = Wifimanager.getconnectioninfo ();

int num = 0;
int sum = 25;
if (Ssid.contains ("Dopool")) {
sum = 35;
}
while (!connectioninfo.getssid (). Contains (SSID) | |
Connectioninfo.getsupplicantstate ()! = supplicantstate.completed | |
Ssid.contains ("Dopool")?!getwifiinfohint (ConnectionInfo): false) {
Sendmsg (Connectioninfo.getssid () + "DD" + SSID + connectioninfo.getsupplicantstate () + getwifiinfohint (connectionInfo) );
ConnectionInfo = Wifimanager.getconnectioninfo ();
try {
num++;
if (num = = SUM) {
SENDMSG (SSID + "exception");
Return
}

To avoid a program that has been in a while loop, let it sleep for 100 milliseconds to detect ...
Thread.Sleep (200);
} catch (Interruptedexception IE) {
}
}

for (int i = 0; i < saveconfigurenetworks.size (); i++) {
Wifimanager.addnetwork (Saveconfigurenetworks.get (i));
}


Sendmsg (Connectioninfo.tostring ());
SENDMSG (SSID + "Connection succeeded!");
} catch (Exception e) {
Todo:handle exception
SENDMSG (SSID + "exception");
E.printstacktrace ();
}
}
}

private static Boolean Ishexwepkey (String wepkey) {
final int len = Wepkey.length ();

WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
if (len! = && Len! =) && len! = 58) {
return false;
}

Return Ishex (Wepkey);
}

private static Boolean Ishex (String key) {
for (int i = Key.length ()-1; I >= 0; i--) {
Final char C = key.charat (i);
if (! ( C >= ' 0 ' && C <= ' 9 ' | | C >= ' A ' && C <= ' F ' | | C >= ' a '
&& c <= ' F ')) {
return false;
}
}
return true;
}

Public list<wificonfiguration> Cleanwificonfigurednetworks (String SSID) {
list<wificonfiguration> Configurednetworks = Wifimanager
. Getconfigurednetworks ();

for (int i = 0; i < configurednetworks.size (); i++) {
Wifimanager.removenetwork (Configurednetworks.get (i). Networkid);
}
return configurednetworks;
}


Arraylist<scanresult> list;

Public list<scanresult> Getnodopoolwifi () {
list<scanresult> Msortwifi = Getsortwifi ();
Get rid of WiFi with Dopool
for (int i = 0; i < msortwifi.size (); i++) {
if (Msortwifi.get (i). Ssid.contains ("Dopool")) {
Msortwifi.remove (i);
}
}
return Msortwifi;
}


Public list<scanresult> Getsortwifi () {

Wifimanager.startscan ();
List = (arraylist<scanresult>) wifimanager.getscanresults ();
arraylist<scanresult> scanresults = new arraylist<> ();

Remove the name of the duplicate WiFi SSID
for (int i = 0; i < list.size (); i++) {
if (List.get (i). Ssid.equals ("") | | List.get (i). Frequency > 3000) {
Continue
}

for (int j = 0; J <= Scanresults.size (); j + +) {
if (j = = Scanresults.size ()) {
Scanresults.add (List.get (i));
Break
} else if (Scanresults.get (j). Ssid.equals (List.get (i). SSID)) {
Break
}
}
}
Sort by signal strength
for (int i = 0; i < scanresults.size (); i++) {
for (int j = 0; J < Scanresults.size (); j + +) {
if (Scanresults.get (i). Level > Scanresults.get (j). Level) {
Scanresult temp = null;
temp = Scanresults.get (i);
Scanresults.set (I, Scanresults.get (j));
Scanresults.set (J, temp);
}
}
}
return scanresults;
}

Calling the Hide method from the reflection method
public boolean getwifiinfohint (Wifiinfo connectioninfo) throws Instantiationexception {
Class AClass = Connectioninfo.getclass ();
try {
Method getmeteredhint = Aclass.getdeclaredmethod ("Getmeteredhint");
Getmeteredhint.setaccessible (TRUE);
Object invoke = Getmeteredhint.invoke (ConnectionInfo);
Return (Boolean) invoke;
} catch (Nosuchmethodexception e) {
E.printstacktrace ();
} catch (Illegalaccessexception e) {
E.printstacktrace ();
} catch (InvocationTargetException e) {
E.printstacktrace ();
}
return false;
}


}

  

Android WiFi usage Record

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.