Android实时获得周围wifi信息(SSID,强度等)

转载请注明出处,谢谢!

1.首先在Manifext里声明权限:

android:name="android.permission.ACCESS_WIFI_STATE" />
android:name="android.permission.INTERNET" />
android:name="android.permission.ACCESS_NETWORK_STATE" />
android:name="android.permission.CHANGE_NETWORK_STATE"/>
android:name="android.permission.CHANGE_WIFI_STATE"/>

2.创建一个TextView用来显示wifi信息:


xml version="1.0" encoding="utf-8"?>
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="com.edu.tongji.wifi_around.MainActivity">

            android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

3.然后是MianActivity:

package com.edu.tongji.wifi_around;

import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView)findViewById(R.id.textView);
        ScanWifiInfo();
        //写线程
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while(true)
                {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ScanWifiInfo();
                        }
                    });
                    try{Thread.sleep(500);}catch(InterruptedException e){e.printStackTrace();}
                }
            }
        });
        t.start();
    }
    private void ScanWifiInfo(){
        WifiManager wifiManager= (WifiManager) getSystemService(WIFI_SERVICE);
        wifiManager.startScan(); //启动扫描
        StringBuilder scanBuilder= new StringBuilder();
        List scanResults=wifiManager.getScanResults();//搜索到的设备列表
        for (ScanResult scanResult : scanResults) {
            scanBuilder.append("\n设备名:"+scanResult.SSID
                    +"\n信号强度:"+wifiManager.calculateSignalLevel(scanResult.level,1001)+"\n");
        }
        textView.setText(scanBuilder)}
}


最后是效果图:


wifi强度会实时改变


如有问题请在下方评论处留言。

你可能感兴趣的:(Android实时获得周围wifi信息(SSID,强度等))