Method of wifi Scan and Connection by Android Programming
- 2021-08-21 21:21:42
- OfStack
This paper describes the method of wifi scanning and connection by Android programming. 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) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUtils = new WifiUtils(this);
findViews();
setLiteners();
}
private void findViews() {
this.search_btn = (Button) findViewById(R.id.search_btn);
this.wifi_lv = (ListView) findViewById(R.id.wifi_lv);
}
private void setLiteners() {
search_btn.setOnClickListener(this);
wifi_lv.setOnItemClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.search_btn) {
showDialog();
new MyAsyncTask().execute();
}
}
/**
* init dialog and show
*/
private void showDialog() {
progressdlg = new ProgressDialog(this);
progressdlg.setCanceledOnTouchOutside(false);
progressdlg.setCancelable(false);
progressdlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressdlg.setMessage(getString(R.string.wait_moment));
progressdlg.show();
}
/**
* dismiss dialog
*/
private void progressDismiss() {
if (progressdlg != null) {
progressdlg.dismiss();
}
}
class MyAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
// Scan nearby WIFI Information
result = mUtils.getScanWifiResult();
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDismiss();
initListViewData();
}
}
private void initListViewData() {
if (null != result && result.size() > 0) {
wifi_lv.setAdapter(new ArrayAdapter<String>(
getApplicationContext(), R.layout.wifi_list_item,
R.id.ssid, result));
} else {
wifi_lv.setEmptyView(findViewById(R.layout.list_empty));
}
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
TextView tv = (TextView) arg1.findViewById(R.id.ssid);
if (!TextUtils.isEmpty(tv.getText().toString())) {
Intent in = new Intent(MainActivity.this, WifiConnectActivity.class);
in.putExtra("ssid", tv.getText().toString());
startActivity(in);
}
}
}
/**
* Connect 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 Yeah ssid
private String ssid;
private String pwd;
private ProgressDialog progressdlg = null;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0:
showToast("WIFI Connection succeeded ");
finish();
break;
case 1:
showToast("WIFI Connection failed ");
break;
}
progressDismiss();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
mUtils = new WifiUtils(this);
findViews();
setLiteners();
initDatas();
}
/**
* init dialog
*/
private void progressDialog() {
progressdlg = new ProgressDialog(this);
progressdlg.setCanceledOnTouchOutside(false);
progressdlg.setCancelable(false);
progressdlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressdlg.setMessage(getString(R.string.wait_moment));
progressdlg.show();
}
/**
* dissmiss dialog
*/
private void progressDismiss() {
if (progressdlg != null) {
progressdlg.dismiss();
}
}
private void initDatas() {
ssid = getIntent().getStringExtra("ssid");
if (!TextUtils.isEmpty(ssid)) {
ssid = ssid.replace("\"", "");
}
this.wifi_ssid_tv.setText(ssid);
}
private void findViews() {
this.connect_btn = (Button) findViewById(R.id.connect_btn);
this.wifi_ssid_tv = (TextView) findViewById(R.id.wifi_ssid_tv);
this.wifi_pwd_tv = (EditText) findViewById(R.id.wifi_pwd_tv);
}
private void setLiteners() {
connect_btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.connect_btn) {// Under 1 Step operation
pwd = wifi_pwd_tv.getText().toString();
// Judge the password input situation
if (TextUtils.isEmpty(pwd)) {
Toast.makeText(this, " Please enter wifi Password ", Toast.LENGTH_SHORT).show();
return;
}
progressDialog();
// Handle various businesses in sub-threads
dealWithConnect(ssid, pwd);
}
}
private void dealWithConnect(final String ssid, final String pwd) {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
// Verify that the password is entered correctly
boolean pwdSucess = mUtils.connectWifiTest(ssid, pwd);
try {
Thread.sleep(4000);
} catch (Exception e) {
e.printStackTrace();
}
if (pwdSucess) {
mHandler.sendEmptyMessage(0);
} else {
mHandler.sendEmptyMessage(1);
}
}
}).start();
}
private void showToast(String str) {
Toast.makeText(WifiConnectActivity.this, str, Toast.LENGTH_SHORT).show();
}
}
Tool class:
public class WifiUtils {
// Context Context Object
private Context mContext;
// WifiManager Object
private WifiManager mWifiManager;
public WifiUtils(Context mContext) {
this.mContext = mContext;
mWifiManager = (WifiManager) mContext
.getSystemService(Context.WIFI_SERVICE);
}
/**
* Determine whether the mobile phone is connected to Wifi Upper
*/
public boolean isConnectWifi() {
// Get ConnectivityManager Object
ConnectivityManager conMgr = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
// Get NetworkInfo Object
NetworkInfo info = conMgr.getActiveNetworkInfo();
// The way to get the connection is wifi
State wifi = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState();
if (info != null && info.isAvailable() && wifi == State.CONNECTED)
{
return true;
} else {
return false;
}
}
/**
* Gets the connection of the current mobile phone wifi Information
*/
public WifiInfo getCurrentWifiInfo() {
return mWifiManager.getConnectionInfo();
}
/**
* Add 1 Network and connected Pass in parameters: WIFI Occurrence configuration class WifiConfiguration
*/
public boolean addNetwork(WifiConfiguration wcg) {
int wcgID = mWifiManager.addNetwork(wcg);
return mWifiManager.enableNetwork(wcgID, true);
}
/**
* Search for nearby hot spot information and return all hot spots as information SSID Aggregate data
*/
public List<String> getScanWifiResult() {
// Scanned hot spot data
List<ScanResult> resultList;
// Start scanning hot spots
mWifiManager.startScan();
resultList = mWifiManager.getScanResults();
ArrayList<String> ssids = new ArrayList<String>();
if (resultList != null) {
for (ScanResult scan : resultList) {
ssids.add(scan.SSID);// Traverse the data and get ssid Data set
}
}
return ssids;
}
/**
* Connect wifi Parameters: wifi Adj. ssid And wifi Password of
*/
public boolean connectWifiTest(final String ssid, final String pwd) {
boolean isSuccess = false;
boolean flag = false;
mWifiManager.disconnect();
boolean addSucess = addNetwork(CreateWifiInfo(ssid, pwd, 3));
if (addSucess) {
while (!flag && !isSuccess) {
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
String currSSID = getCurrentWifiInfo().getSSID();
if (currSSID != null)
currSSID = currSSID.replace("\"", "");
int currIp = getCurrentWifiInfo().getIpAddress();
if (currSSID != null && currSSID.equals(ssid) && currIp != 0) {
isSuccess = true;
} else {
flag = true;
}
}
}
return isSuccess;
}
/**
* Create WifiConfiguration Object Divide into 3 This kind of situation: 1 No password ;2 Use wep Encryption ;3 Use wpa Encryption
*
* @param SSID
* @param Password
* @param Type
* @return
*/
public WifiConfiguration CreateWifiInfo(String SSID, String Password,
int Type) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
WifiConfiguration tempConfig = this.IsExsits(SSID);
if (tempConfig != null) {
mWifiManager.removeNetwork(tempConfig.networkId);
}
if (Type == 1) // WIFICIPHER_NOPASS
{
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (Type == 2) // WIFICIPHER_WEP
{
config.hiddenSSID = true;
config.wepKeys[0] = "\"" + Password + "\"";
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (Type == 3) // 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);
// 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;
}
private WifiConfiguration IsExsits(String SSID) {
List<WifiConfiguration> existingConfigs = mWifiManager
.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
return existingConfig;
}
}
return null;
}
}
--Related layout files--
Main page
<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" >
<Button
android:id="@+id/search_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text=" Search nearby WIFI"
android:textSize="16sp" >
</Button>
<ListView
android:id="@+id/wifi_lv"
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: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" >
<TextView
android:id="@+id/wifi_ssid"
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:id="@+id/wifi_ssid_tv"
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:id="@+id/wifi_pwd"
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:id="@+id/wifi_pwd_tv"
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:id="@+id/connect_btn"
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>
item of main page ListView
<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="40dp"
android:background="#FFFFFF" >
<TextView
android:id="@+id/ssid"
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 display of WIFI was not searched in the main interface
<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:background="#FFFFFF" >
<TextView
android:id="@+id/ssid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text=" There is no nearby for the time being WIFI"
android:textColor="#333333"
android:textSize="16sp" />
</RelativeLayout>
Download address of DEMO on github: https://github.com/ldm520/WIFI_TOOL
More readers interested in Android can check the topics of this site: "Summary of Android Communication Mode", "Summary of Android Hardware Related Operation and Application", "Summary of Android Resource Operation Skills", "Summary of View Skills in Android View", "Introduction and Advanced Tutorial of Android Development" and "Summary of Android Control Usage"
I hope this article is helpful to everyone's Android programming.