Android Development Step by step 48: Automatically connect to a WiFi hotspot via Wifimanager

Source: Internet
Author: User
Tags network function

Recently participated in an interview with a startup company, they did an application, that is, users open their app to provide free internet access, and then the interview process, the Buddy said, you on the WiFi protocol you understand? Need to use the lower level of things, oh, I'm going to go, just such a network function needs very low ground? Make a very advanced appearance, really the bottom is related to modify the Android frame, modify the phone rom, you do this step? No, just implemented on the basis of the Android framework API, so I experimented with it today. It's just a matter of 10 minutes before I get caught up in you, the amount ...

The development process mainly uses the service which the Wifimanager this system comes with, it has the following several states

Wifimanager.wifi_state_disabled://wifi Not available

Wifimanager.wifi_state_disabling://wifi is shutting down or disconnecting

Wifimanager.wifi_state_enabled://wifi already open available

Wifimanager.wifi_state_enabling://wifi is opening or connecting

wifimanager.wifi_state_unknown://Unknown message

OK, let's start our experiment:

Step One: Androidmanifest.xml Add related permissions

<uses-permission android:name= "Android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name= "Android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name= "Android.permission.INTERNET"/>
<uses-permission android:name= "Android.permission.WAKE_LOCK"/>

Step Two: Create a new test page/study/res/layout/activity_wifi.xml

<relativelayout xmlns:android= " http:// Schemas.android.com/apk/res/android "
    xmlns:tools=" http://schemas.android.com/tools "
    android:layout_width= "match_parent"
    android:layout_height= "match_parent "
    android:paddingbottom=" @dimen/activity_vertical_margin "
    android: paddingleft= "@dimen/activity_horizontal_margin"
    android:paddingright= "@dimen/activity_ Horizontal_margin "
    android:paddingtop=" @dimen/activity_vertical_margin "
     tools:context= ". Mainactivity ";

<button
Android:id= "@+id/btnwifi"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:layout_margintop= "47DP"
android:text= "Auto Connect WiFi"/>

</RelativeLayout>

Step three: Realize Activity,wifimanagertestactivity.java

/**
* Automatically choose to connect a WiFi signal
*/
Package com.figo.study;

Import java.util.List;

import android.app.Activity;
Import Android.content.Context;
Import android.net.wifi.WifiConfiguration;
Import Android.net.wifi.WifiConfiguration.AuthAlgorithm;
Import Android.net.wifi.WifiConfiguration.KeyMgmt;
Import Android.net.wifi.WifiManager;
Import Android.os.Bundle;
Import android.text.TextUtils;
Import Android.util.Log;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;

/**
* @author Zhuzhifei
*/
public class Wifimanagertestactivity extends Activity {
Private Button Btnwifi;
Wifimanager Wifimanager;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_wifi);
Get WiFi Management Service
Wifimanager = (Wifimanager) this.getsystemservice (Context.wifi_service);

Btnwifi = (Button) Findviewbyid (R.id.btnwifi);
Btnwifi.setonclicklistener (New Onclicklistener () {

@Override
public void OnClick (View arg0) {
TODO auto-generated Method Stub
Connect ("NewHome", "newhome123", WIFICIPHERTYPE.WIFICIPHER_WEP);
Start WiFi
Connect ("NewHome", "newhome123", WIFICIPHERTYPE.WIFICIPHER_WPA);
}
});

}

private static final String TAG = Wifimanagertestactivity.class
. Getsimplename ();

Define several encryption methods, one is WEP, the other is WPA, and there are no password cases.
public enum Wificiphertype {
WIFICIPHER_WEP, WIFICIPHER_WPA, Wificipher_nopass, Wificipher_invalid
}


Provides an external interface for incoming wireless network Ssid,password 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.wepkeys[0] = "";
Config.allowedKeyManagement.set (WifiConfiguration.KeyMgmt.NONE);
Config.weptxkeyindex = 0;
}
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 (WifiConfiguration.AuthAlgorithm.OPEN);
Config.allowedGroupCiphers.set (WifiConfiguration.GroupCipher.TKIP);
Config.allowedKeyManagement.set (WifiConfiguration.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;
}
Start a new thread to open WiFi
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 () {
Open wifi
Openwifi ();
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) {
}
}

Wificonfiguration wificonfig = createwifiinfo (SSID, password, type);
//
if (Wificonfig = = null) {
LOG.D (TAG, "Wificonfig is null!");
Return
}

Wificonfiguration tempconfig = isexsits (SSID);

if (tempconfig! = null) {
Wifimanager.removenetwork (Tempconfig.networkid);
}

int NetID = Wifimanager.addnetwork (wificonfig);
Boolean enabled = Wifimanager.enablenetwork (NetID, true);
LOG.D (TAG, "enablenetwork status enable=" + enabled);
Boolean connected = Wifimanager.reconnect ();
LOG.D (TAG, "enablenetwork connected=" + connected);
}
}

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;
}

}

Android Development Step by step 48: Automatically connect to a WiFi hotspot via Wifimanager

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.