This article describes the Android programming method to implement wifi scanning and connection. Share it for your reference, as follows:
Main interface, search for nearby WIFI information
/** * Search WIFI and show in ListView * */ public class MainActivity extends Activity implements OnClickListener, OnItemClickListener { private Button search_btn; private ListView wifi_lv; private WifiUtils mUtils; private List<String> result; private ProgressDialog progressdlg = null; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_main); mUtils = new WifiUtils(this); findViews(); setLiteners(); } private void findViews() { this.search_btn = (Button) findViewById(.search_btn); this.wifi_lv = (ListView) findViewById(.wifi_lv); } private void setLiteners() { search_btn.setOnClickListener(this); wifi_lv.setOnItemClickListener(this); } @Override public void onClick(View v) { if (() == .search_btn) { showDialog(); new MyAsyncTask().execute(); } } /** * init dialog and show */ private void showDialog() { progressdlg = new ProgressDialog(this); (false); (false); (ProgressDialog.STYLE_SPINNER); (getString(.wait_moment)); (); } /** * dismiss dialog */ private void progressDismiss() { if (progressdlg != null) { (); } } class MyAsyncTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... arg0) { //Scan nearby WIFI information result = (); return null; } @Override protected void onPostExecute(Void result) { (result); progressDismiss(); initListViewData(); } } private void initListViewData() { if (null != result && () > 0) { wifi_lv.setAdapter(new ArrayAdapter<String>( getApplicationContext(), .wifi_list_item, , result)); } else { wifi_lv.setEmptyView(findViewById(.list_empty)); } } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { TextView tv = (TextView) (); if (!(().toString())) { Intent in = new Intent(, ); ("ssid", ().toString()); startActivity(in); } } }
/** * Connect to the specified WIFI * */ public class WifiConnectActivity extends Activity implements OnClickListener { private Button connect_btn; private TextView wifi_ssid_tv; private EditText wifi_pwd_tv; private WifiUtils mUtils; // wifi ssid private String ssid; private String pwd; private ProgressDialog progressdlg = null; @SuppressLint("HandlerLeak") private Handler mHandler = new Handler() { public void handleMessage( msg) { switch () { case 0: showToast("WIFI connection is successful"); finish(); break; case 1: showToast("WIFI connection failed"); break; } progressDismiss(); } }; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_connect); mUtils = new WifiUtils(this); findViews(); setLiteners(); initDatas(); } /** * init dialog */ private void progressDialog() { progressdlg = new ProgressDialog(this); (false); (false); (ProgressDialog.STYLE_SPINNER); (getString(.wait_moment)); (); } /** * dissmiss dialog */ private void progressDismiss() { if (progressdlg != null) { (); } } private void initDatas() { ssid = getIntent().getStringExtra("ssid"); if (!(ssid)) { ssid = ("\"", ""); } this.wifi_ssid_tv.setText(ssid); } private void findViews() { this.connect_btn = (Button) findViewById(.connect_btn); this.wifi_ssid_tv = (TextView) findViewById(.wifi_ssid_tv); this.wifi_pwd_tv = (EditText) findViewById(.wifi_pwd_tv); } private void setLiteners() { connect_btn.setOnClickListener(this); } @Override public void onClick(View v) { if (() == .connect_btn) {// Next steps pwd = wifi_pwd_tv.getText().toString(); // Determine password input if ((pwd)) { (this, "Please enter your wifi password", Toast.LENGTH_SHORT).show(); return; } progressDialog(); // Handle various business in child thread dealWithConnect(ssid, pwd); } } private void dealWithConnect(final String ssid, final String pwd) { new Thread(new Runnable() { @Override public void run() { (); // Check whether the password is entered correctly boolean pwdSucess = (ssid, pwd); try { (4000); } catch (Exception e) { (); } if (pwdSucess) { (0); } else { (1); } } }).start(); } private void showToast(String str) { (, str, Toast.LENGTH_SHORT).show(); } }
Tools:
public class WifiUtils { // Context object private Context mContext; // WifiManager object private WifiManager mWifiManager; public WifiUtils(Context mContext) { = mContext; mWifiManager = (WifiManager) mContext .getSystemService(Context.WIFI_SERVICE); } /** * Determine whether the phone is connected to Wifi */ public boolean isConnectWifi() { // Get ConnectivityManager object ConnectivityManager conMgr = (ConnectivityManager) mContext .getSystemService(Context.CONNECTIVITY_SERVICE); // Get NetworkInfo object NetworkInfo info = (); // The way to get the connection is wifi State wifi = (ConnectivityManager.TYPE_WIFI) .getState(); if (info != null && () && wifi == ) { return true; } else { return false; } } /** * Get the wifi information connected to the current mobile phone */ public WifiInfo getCurrentWifiInfo() { return (); } /** * Add a network and connect to the incoming parameter: WifiConfiguration occurs in WIFI */ public boolean addNetwork(WifiConfiguration wcg) { int wcgID = (wcg); return (wcgID, true); } /** * Search for nearby hotspot information and return SSID collection data with all hotspots as information */ public List<String> getScanWifiResult() { // Scanned hotspot data List<ScanResult> resultList; // Start scanning hotspots (); resultList = (); ArrayList<String> ssids = new ArrayList<String>(); if (resultList != null) { for (ScanResult scan : resultList) { ();// traverse the data and obtain the ssid data set } } return ssids; } /** * Connect to wifi Parameters: wifi ssid and wifi password */ public boolean connectWifiTest(final String ssid, final String pwd) { boolean isSuccess = false; boolean flag = false; (); boolean addSucess = addNetwork(CreateWifiInfo(ssid, pwd, 3)); if (addSucess) { while (!flag && !isSuccess) { try { (10000); } catch (InterruptedException e1) { (); } String currSSID = getCurrentWifiInfo().getSSID(); if (currSSID != null) currSSID = ("\"", ""); int currIp = getCurrentWifiInfo().getIpAddress(); if (currSSID != null && (ssid) && currIp != 0) { isSuccess = true; } else { flag = true; } } } return isSuccess; } /** * Create WifiConfiguration object. It can be divided into three situations: 1. No password; 2. Encrypted with wep; 3. Encrypted with wpa. * * @param SSID * @param Password * @param Type * @return */ public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type) { WifiConfiguration config = new WifiConfiguration(); (); (); (); (); (); = "\"" + SSID + "\""; WifiConfiguration tempConfig = (SSID); if (tempConfig != null) { (); } if (Type == 1) // WIFICIPHER_NOPASS { [0] = ""; (); = 0; } if (Type == 2) // WIFICIPHER_WEP { = true; [0] = "\"" + Password + "\""; .set(); (); (); (.WEP40); .set(.WEP104); (); = 0; } if (Type == 3) // WIFICIPHER_WPA { = "\"" + Password + "\""; = true; .set(); (); (.WPA_PSK); .set(); // (); (); .set(); = ; } return config; } private WifiConfiguration IsExsits(String SSID) { List<WifiConfiguration> existingConfigs = mWifiManager .getConfiguredNetworks(); for (WifiConfiguration existingConfig : existingConfigs) { if (("\"" + SSID + "\"")) { return existingConfig; } } return null; } }
——Related layout files———
Main page
<RelativeLayout xmlns:andro xmlns:tools="/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android: android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="Search for nearby WIFI" android:textSize="16sp" > </Button> <ListView android: android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/search_btn" android:layout_marginTop="10dp" android:divider="#d1d1d1" android:dividerHeight="1px" android:scrollbars="none" > </ListView> </RelativeLayout>
Connection page
<RelativeLayout xmlns:andro xmlns:tools="/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:padding="10dp" android:text="@string/wifi_ssid" android:textSize="16sp" /> <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:layout_toRightOf="@id/wifi_ssid" android:padding="10dp" android:textSize="16sp" /> <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/wifi_ssid" android:layout_marginTop="15dp" android:padding="10dp" android:text="@string/wifi_pwd" android:textSize="16sp" /> <EditText android: android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/wifi_ssid_tv" android:layout_marginRight="15dp" android:layout_marginTop="15dp" android:layout_toRightOf="@id/wifi_pwd" android:hint="@string/input_pwd_hint" android:padding="10dp" android:textSize="16sp" /> <Button android: android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_margin="10dp" android:text="Connect WIFI" android:textSize="16sp" > </Button> </RelativeLayout>
The item of the main page ListView
<RelativeLayout xmlns:andro xmlns:tools="/tools" android:layout_width="match_parent" android:layout_height="40dp" android:background="#FFFFFF" > <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerInParent="true" android:paddingLeft="15dp" android:textColor="#333333" android:textSize="16sp" /> </RelativeLayout>
The main interface has not been searched. WIFI display is reached.
<RelativeLayout xmlns:andro xmlns:tools="/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFFFF" > <TextView android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="No WIFI nearby" android:textColor="#333333" android:textSize="16sp" /> </RelativeLayout>
DEMO download address on github:/ldm520/WIFI_TOOL
For more information about Android related content, please check out the topic of this site:Android communication methods summary》、《Android hardware-related operations and application summary》、《Android resource operation skills summary》、《Android View View Tips Summary》、《Android development introduction and advanced tutorial"and"Android control usage summary》
I hope this article will be helpful to everyone's Android programming design.