Android automatically connects to the specified wifi, without a password or a specified password, androidwifi

Source: Internet
Author: User
Tags sendmsg

Android automatically connects to the specified wifi, without a password or a specified password, androidwifi

I. Running status

The following is a requirement: "How to connect to the specified password-free WIFI without scanning (no connection before)", so I wrote a Demo, status when the connection is not successful. The first edit box asks the user to enter the SSID, and the second edit box to enter the password. The password can be entered Based on the instance situation or not, because some Wi-Fi is password-free. Password-free is not used to crack the Wi-Fi password. Note that the Wi-Fi icon on the top of the mobile phone in the picture does not exist, indicating that the wifi of the mobile phone is not enabled at this time. The running status on the mobile phone is as follows:

Enter the SSID and click the status after connection. When the phone's wifi is not enabled, the program will automatically turn on the wifi, and then connect to the specified wifi.

The mobile phone information for the test is as follows:

Ii. function implementation

2.1. The project structure is as follows:

2.2. the activity_main.xml file of the page layout is as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/txtSSID"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="SSID:"        android:textSize="@dimen/activity_horizontal_margin" />    <EditText        android:id="@+id/editSSID"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:ems="10"        android:text="FBI" >        <requestFocus />    </EditText>    <TextView        android:id="@+id/TextView01"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Password:"        android:textSize="@dimen/activity_horizontal_margin" />    <EditText        android:id="@+id/editPwd"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:ems="10"        android:text="" />    <Button        android:id="@+id/btnConnect"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Connect" />    <TextView        android:id="@+id/txtMessage"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="" /></LinearLayout>

 

2.3 The configuration file AndroidManifest. xml contains the following content. It is very important to add user permissions for wifi access in the middle.

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.wifigo"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="14"        android:targetSdkVersion="19" />    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >    </uses-permission>    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

2.4 Wifi connection management WifiConnector. java, many of which refer to enthusiastic blogs. Thank you!

Package com. example. wifigo; import java. util. list; import android.net. wifi. *; import android.net. wifi. wifiConfiguration. authAlgorithm; import android.net. wifi. wifiConfiguration. keyMgmt; import android. OS. handler; import android. OS. message; import android. text. textUtils; import android. util. log; public class WifiConnector {Handler mHandler; WifiManager wifiManager;/*** send a message to the UI * @ param info message */public v Oid sendMsg (String info) {if (mHandler! = Null) {Message msg = new Message (); msg. obj = info; mHandler. sendMessage (msg); // send a message to Handler} else {Log. e ("wifi", info) ;}// WIFICIPHER_WEP is WEP, WIFICIPHER_WPA is WPA, WIFICIPHER_NOPASS has no password public enum WifiCipherType {signature, signature, WIFICIPHER_NOPASS, WIFICIPHER_INVALID} // constructor public WifiConnector (WifiManager wifiManager) {this. wifiManager = wifiManager;} // provides an external interface for incoming Public void connect (String ssid, String password, WifiCipherType) {Thread thread = new Thread (new ConnectRunnable (ssid, password, type); thread. start () ;}// check whether the network private WifiConfiguration isExsits (String SSID) {List <WifiConfiguration> existingConfigs = wifiManager has been configured. getConfiguredNetworks (); for (WifiConfiguration existingConfig: existingConfigs) {if (existingConfig. SSID. e Quals ("\" "+ 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 (WifiConfiguration. 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. preSharedK Ey = "\" "+ 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 it here; otherwise, it cannot be automatically reconnected. // config. allowedProtocols. set (WifiConfigur Ation. 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;} class ConnectRunnable implements Runnable {private String ssid; private String password; private WifiCipherType; public ConnectRunnable (String ssid, String password, WifiCipherType) {this. ssid = ssid; this. password = password; this. type = type ;}@ Override public void run () {try {// enable wifi openWif I (); sendMsg ("opened"); Thread. sleep (200); // it may take some time to enable the wifi function (it usually takes about 1-3 seconds to test the function on the mobile phone ), so the following statement 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) {sendMsg ("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); sendMsg ("enableNetwork status enable =" + enabled); boolean connected = wifiManager. reconnect (); sendMsg ("enableNetwork connected =" + connected); sendMsg ("connection successful! ");} Catch (Exception e) {// TODO: handle exception sendMsg (e. getMessage (); 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! = 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 ;}}

2.5. The MainActivity. java code completes receiving user input and calling the wifi connection function, as shown below:

Package com. example. wifigo; import com. example. wifigo. wifiConnector. wifiCipherType; import android. app. activity; import android. content. context; import android.net. wifi. wifiManager; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. menu; import android. view. menuItem; import android. view. view; import android. widget. button; import android. widget. editText; import Ndroid. widget. textView; import android. widget. toast; public class MainActivity extends Activity {Button btnConnect; WifiManager wifiManager; WifiConnector wac; TextView textView1; EditText editPwd; EditText editSSID; @ Override protected void onCreate (Bundle listener. onCreate (savedInstanceState); setContentView (R. layout. activity_main); btnConnect = (Button) findViewById (R. id. btnCo Nnect); textView1 = (TextView) findViewById(R.id.txt Message); wifiManager = (WifiManager) getSystemService (Context. WIFI_SERVICE); wac = new WifiConnector (wifiManager); editPwd = (EditText) findViewById (R. id. editPwd); editSSID = (EditText) findViewById (R. id. editSSID); wac. mHandler = new Handler () {@ Override public void handleMessage (Message msg) {// operation interface textView1.setText (textView1.getText () + "\ n" + msg. Obj + ""); super. handleMessage (msg) ;}}; btnConnect. setOnClickListener (new Button. onClickListener () {@ Override public void onClick (View v) {try {wac. connect (editSSID. getText (). toString (), editPwd. getText (). toString (), editPwd. getText (). toString (). equals ("")? WifiCipherType. WIFICIPHER_NOPASS: WifiCipherType. WIFICIPHER_WPA);} catch (Exception e) {textView1.setText (e. getMessage () ;}}}) ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}@ Override public boolean onOptionsItemSelected (MenuItem item) {// Handle action bar item clicks here. the action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest. xml. int id = item. getItemId (); if (id = R. id. action_settings) {return true;} return super. onOptionsItemSelected (item );}}

2.6 Summary

The time is tight and the code is rough. After all, this is just a demo. If you need to use it in a commercial project, it may only serve as an example; in addition, during the test, if the phone's wifi is not turned on, the program will crash when the program is turned on. Later, it may take some time to turn on the wifi, therefore, some manual delayed operations are added to the Code, which should be replaced by a more elegant method. I use an Android 4. x. x's meizu note 1 phone and a DLink DIR-600N of the old router test no problem, use your laptop as a hot spot, with a password connection no problem, this does not mean that it is normal in other environments.

2.7. Reference example:

Download sample source code

 

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.