1. First, add the following code to the Android manifest.xml file to enable permissions:
<! -- access to WiFi status -- > <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <! -- permission to change network state -- > <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/> <! -- get network permission -- > <uses-permission android:name="android.permission.INTERNET"/> <! -- write data permission to SDCard -- > <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <! -- create and delete file permissions in SDCard -- > <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
2.Android has three classes related to obtaining WiFi information: WiFi manager, WiFi, ScanResult
- WifiManage
1 / / obtain the system wifi service 2 WifiManage wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); 3 / / obtain the information about the currently connected wifi 4 WifiInfo wi = wm.getConnectionInfo(); 5 / / obtain all the wifi information scanned 6 List<ScanResult> scanResults = wm.getScanResults(); 7 / / obtain the current wifi card status of the mobile phone 8 int state = WM. Getwifi state(); / / state value is defined as the following macro 9 WiFi manager.wifi? State? Enabled WiFi network card available 10 WiFi manager.wifi? State? Disabled WiFi network card is not available 11 WiFi manager.wifi? State? Disabling WiFi network card is shutting down 12 WiFi manager.wifi? State? Enabling WiFi network card is opening 13 WiFi manager.wifi ﹣ state ﹣ unknown state
- WifiInfo
1 WifiInfo wifiInfo = wifi_service.getConnectionInfo(); // Get the current connection wifi Information 2 wi.getSSID(); // Get current connection wifi NOUN 3 wi.getBSSID(); // Get router Mac Address, String type 4 wi.getMacAddress(); // Get this machine Mac address 5 wi.getRssi(); // Get current connection wifi Signal strength of, return a 0~-100 Between int Type data 6 wi.getLinkSpeed(); // Get connection speed 7 WifiInfo.LINK_SPEED_UNITS; // Connection speed unit
Note: RSSI, the value obtained is an interval value of 0 to - 100, which is an int type data. 0 to - 50 indicates the best signal, and - 50 to - 70 indicates the signal deviation, and less than - 70 indicates the worst. It may not be connected or dropped. Generally, if Wifi is broken, the value is - 200.
- ScanResult
scanResult.SSID(); scanResult.BSSID(); scanResult.level; // signal intensity(Raw data) WifiManager.calculateSignalLevel(scanResult.level(),5); // Calculate the strength grade, which is divided into 5 grades.
3. code
- Activity > main.xml resource file
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.lee.rss_collector.MainActivity"> <RelativeLayout android:id="@+id/relative_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="30dp" android:gravity="start|center_vertical"> <Button android:id="@+id/start_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_marginStart="20dp" android:text="@string/start_scan" /> <Button android:id="@+id/stop_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_toEndOf="@+id/start_button" android:text="@string/stop_scan" /> <Button android:id="@+id/save_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_toEndOf="@+id/stop_button" android:text="@string/save_button" /> <LinearLayout android:id="@+id/curr_connected" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/start_button" android:layout_marginTop="10dp" android:orientation="vertical"> <TextView android:id="@+id/text_view_curr_connected" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/curConnectWiFi" /> <EditText android:id="@+id/edit_text_curr_connected" android:layout_width="match_parent" android:layout_height="wrap_content" android:cursorVisible="false" android:focusable="false" android:focusableInTouchMode="false" /> </LinearLayout> <LinearLayout android:id="@+id/scan_result" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_below="@+id/curr_connected"> <TextView android:id="@+id/text_view_scan_result" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="20dp" android:text="@string/scanResult" /> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:fadingEdge="vertical" android:scrollbars="vertical"> <LinearLayout android:id="@+id/list_wifi" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <EditText android:id="@+id/edit_view_scan_result" android:layout_width="match_parent" android:layout_height="wrap_content" android:cursorVisible="false" android:focusable="false" android:focusableInTouchMode="false" /> </LinearLayout> </ScrollView> </LinearLayout> </RelativeLayout> <android.support.constraint.Guideline android:id="@+id/guideline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintGuide_begin="20dp" /> <android.support.constraint.Guideline android:id="@+id/guideline2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_begin="20dp" /> <android.support.constraint.Group android:id="@+id/group" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </android.support.constraint.ConstraintLayout>
- MainActivity.java main program
package com.lee.rss_collector; import android.content.Context; import android.net.wifi.ScanResult; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import java.io.FileOutputStream; import java.util.List; public class MainActivity extends AppCompatActivity { // private Context mContext = getApplicationContext(); // Add this sentence and it will flash back public boolean mFlag = true; // Control thread termination private String mCurrentConnect; // Save the current connection WiFi information private StringBuilder mListInfo;// Save scanned WiFi List information private ScanThread mScanThread; // WiFi Scanned threads @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Show main page setContentView(R.layout.activity_main); // Monitor three buttons findViewById(R.id.start_button).setOnClickListener(mOnClickListener); findViewById(R.id.stop_button).setOnClickListener(mOnClickListener); findViewById(R.id.save_button).setOnClickListener(mOnClickListener); } public View.OnClickListener mOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()){ case R.id.start_button: mFlag = true; // Sign location is true,Allow threads to run mScanThread = new ScanThread(); // Newly build WiFi Scanning thread mScanThread.start(); // Startup thread break; case R.id.stop_button: mFlag = false; // Sign location is false,Thread termination break; case R.id.save_button: String filename = "wifi_data.txt"; String fileContent = mListInfo.toString(); try{ savaFileToSD(filename,fileContent); Toast.makeText(getApplicationContext(), "Data written successfully", Toast.LENGTH_SHORT).show(); }catch (Exception e){ e.printStackTrace(); Toast.makeText(getApplicationContext(), "Data write failed", Toast.LENGTH_SHORT).show(); } break; } } }; private class ScanThread extends Thread { @Override public void run() { while (mFlag) { // stay UI Get in thread WiFi Information and update UI runOnUiThread(new Runnable() { @Override public void run() { obtainListInfo(); } }); // Sampling frequency 500 ms try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } private void obtainListInfo(){ WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); WifiInfo wi = wm.getConnectionInfo(); String ssid = wi.getSSID(); String bssid = wi.getBSSID(); int rssi = wi.getRssi(); int speed = wi.getLinkSpeed(); // Record the current connection WiFi information mCurrentConnect = "SSID: " + ssid + "\nMAC Address: " + bssid + "\nSignal Strength(dBm): " + rssi + "\nspeed: " + speed + " " + WifiInfo.LINK_SPEED_UNITS; // Record scanned WiFi List information if (wm.getWifiState() == WifiManager.WIFI_STATE_ENABLED) { mListInfo = new StringBuilder(); List<ScanResult> scanResults = wm.getScanResults(); for (ScanResult sr:scanResults){ mListInfo.append("SSID: "); mListInfo.append(sr.SSID); mListInfo.append("\nMAC Address: "); mListInfo.append(sr.BSSID); mListInfo.append("\nSignal Strength(dBm): "); mListInfo.append(sr.level); mListInfo.append("\n\n"); } // To update UI Up display WiFi information EditText editTextCurr = findViewById(R.id.edit_text_curr_connected); EditText editTextList = findViewById(R.id.edit_view_scan_result); editTextCurr.setText(mCurrentConnect); editTextList.setText(mListInfo.toString()); } } //to SD The method of card writing file public void savaFileToSD(String filename,String fileContent) throws Exception { // Judge whether there is SD Card and read SD Authority of card if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // Set file path String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename; // new A file output stream object FileOutputStream output = new FileOutputStream(filePath); //take String The string is written to the output stream as a byte stream output.write(fileContent.getBytes()); output.close(); //Close output stream } else { Toast.makeText(MainActivity.this, "SD Card does not exist or is not readable or writable", Toast.LENGTH_SHORT).show(); } } }