Android development step by step 48: automatically connect to a Wi-Fi hotspot through WifiManager, androidwifimanager

Source: Internet
Author: User

Android development step by step 48: automatically connect to a Wi-Fi hotspot through WifiManager, androidwifimanager

Recently, I attended an interview with a startup company. They made an application, that is, users can open their application to provide free Internet access. Then, during the interview, the buddy said, do you understand wifi protocols? I need to use something at the underlying level. Do I need such an online function at the underlying level? The underlying architecture involves modifying the android framework and modifying the ROM of the mobile phone. Have you done this? No, it is implemented based on the api provided by the android framework. To this end, I have made a special experiment today. In just 10 minutes, I was taken care of by you...

WifiManager is mainly used in the development process. It has the following statuses:

WifiManager. WIFI_STATE_DISABLED: // wifi unavailable

WifiManager. WIFI_STATE_DISABLING: // wifi is being disabled or disconnected

WifiManager. WIFI_STATE_ENABLED: // wifi enabled and available

WifiManager. WIFI_STATE_ENABLING: // wifi is on or connected

WifiManager. WIFI_STATE_UNKNOWN: // unknown message

Okay. Start our experiment:

Step 1: Add related permissions to AndroidManifest. xml

<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 2: Create a 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 = "automatically connect to wifi"/>

</RelativeLayout>

 

Step 3: implement Activity and WifiManagerTestActivity. java

/**
* Automatically select a Wi-Fi 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 the 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: WEP, WPA, and password-free.
Public enum WifiCipherType {
WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
}


// Provides an external interface to pass in the wireless network ssid, password,
Public void connect (String ssid, String password, WifiCipherType ){
Thread thread = new Thread (new ConnectRunnable (ssid, password, type ));
Thread. start ();
}

// Check whether the network has been configured before
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 );
// This must be modified. Otherwise, automatic reconnection is not allowed.
// 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;
}

// Enable the wifi Function
Private boolean openWifi (){
Boolean bRet = true;
If (! WifiManager. isWifiEnabled ()){
BRet = wifiManager. setWifiEnabled (true );
}
Return bRet;
}
// Start a new thread to enable wifi
Class ConnectRunnable implements Runnable {
Private String ssid;

Private String password;

Private WifiCipherType;

Public ConnectRunnable (String ssid, String password, WifiCipherType type ){
This. ssid = ssid;
This. password = password;
This. type = type;
}

@ Override
Public void run (){
// Enable wifi
OpenWifi ();
// It may take some time to enable the wifi function (it usually takes about 1-3 seconds to test on the mobile phone ).
// The following statement can be executed only when the status changes to WIFI_STATE_ENABLED.
While (wifiManager. getWifiState () = WifiManager. WIFI_STATE_ENABLING ){
Try {
// To prevent the program from having a while LOOP, let it sleep for 100 ms detection ......
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! = 10 & len! = 26 & 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;
}

}

 


In android development, how can I enable the Wi-Fi hotspot through code implementation?

1. Apply for permissions:
Android. permission. ACCESS_WIFI_STATE
Android. permission. CHANGE_WIFI_STATE
Android. permission. WAKE_LOCK
2. Get WifiManager
WifiManager = (WifiManager) this. getSystemService (Context. WIFI_SERVICE );
3. Enable and disable wifi
If (wifiManager. isWifiEnabled ()){
WifiManager. setWifiEnabled (false );
} Else {
WifiManager. setWifiEnabled (true );
}
4. Note
If you encounter force-close, select wait, because it takes several seconds to start wifi. If the UI hasn't been reflected in five minutes, the system will give you this force close exception.

PS: I used to design and read system hardware information before, but it has been useless for a long time. This comment is sent from the Internet, hoping to help you.

In android wifi development, how does one determine that a specified Wi-Fi hotspot is successfully connected?

Turn off the signal and see if there is any signal interaction. If yes, It is not connected.
 

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.