开发 Android 的 WiFi 扫描器


此示例演示如何为 Android 开发 WiFi 扫描器

步骤 1 − 在 Android Studio 中创建新项目,转到“文件 ⇒ 新项目”并填写所有必需详细信息以创建一个新项目。

步骤 2 − 在 res/layout/activity_main.xml 中添加以下代码。

<?xml version = "1.0" encoding = "utf-8"?>
<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:layout_margin = "16dp"
   android:orientation = "vertical"
   tools:context = ".MainActivity">
   <ListView
      android:id = "@+id/wifiList"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent"
      android:layout_above = "@+id/scanBtn" />
   <Button
      android:id = "@+id/scanBtn"
      android:layout_width = "match_parent"
      android:layout_height = "50dp"
      android:layout_alignParentBottom = "true"
      android:layout_gravity = "bottom"
      android:layout_margin = "15dp"
      android:text = "Scan WiFi" />
</RelativeLayout>

步骤 3 − 在 src/MainActivity.java 中添加以下代码

package com.example.myapplication;

import android.Manifest;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
   private ListView wifiList;
   private WifiManager wifiManager;
   private final int MY_PERMISSIONS_ACCESS_COARSE_LOCATION = 1;
   WifiReceiver receiverWifi;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      wifiList = findViewById(R.id.wifiList);
      Button buttonScan = findViewById(R.id.scanBtn);
      wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
      if (!wifiManager.isWifiEnabled()) {
         Toast.makeText(getApplicationContext(), "Turning WiFi ON...", Toast.LENGTH_LONG).show();
         wifiManager.setWifiEnabled(true);
      }
      buttonScan.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
               ! = PackageManager.PERMISSION_GRANTED) {
               ActivityCompat.requestPermissions(
                  MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_ACCESS_COARSE_LOCATION);
               } else {
                  wifiManager.startScan();
               }
            }
         });
      }
      @Override
      protected void onPostResume() {
         super.onPostResume();
         receiverWifi = new WifiReceiver(wifiManager, wifiList);
         IntentFilter intentFilter = new IntentFilter();
         intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
         registerReceiver(receiverWifi, intentFilter);
         getWifi();
      }
      private void getWifi() {
         if (Build.VERSION.SDK_INT > = Build.VERSION_CODES.M) {
            Toast.makeText(MainActivity.this, "version> = marshmallow", Toast.LENGTH_SHORT).show();
            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) ! = PackageManager.PERMISSION_GRANTED) {
               Toast.makeText(MainActivity.this, "location turned off", Toast.LENGTH_SHORT).show();
               ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_ACCESS_COARSE_LOCATION);
            } else {
               Toast.makeText(MainActivity.this, "location turned on", Toast.LENGTH_SHORT).show();
               wifiManager.startScan();
            }
         } else {
            Toast.makeText(MainActivity.this, "scanning", Toast.LENGTH_SHORT).show();
            wifiManager.startScan();
         }
      }
      @Override
      protected void onPause() {
         super.onPause();
         unregisterReceiver(receiverWifi);
      }
      @Override
      public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
         super.onRequestPermissionsResult(requestCode, permissions, grantResults);
         switch (requestCode) {
            case MY_PERMISSIONS_ACCESS_COARSE_LOCATION:
            if (grantResults.length > 0 && grantResults[0] = = PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(MainActivity.this, "permission granted", Toast.LENGTH_SHORT).show();
            wifiManager.startScan();
         } else {
            Toast.makeText(MainActivity.this, "permission not granted", Toast.LENGTH_SHORT).show();
            return;
         }
         break;
      }
   }
}

步骤 4 − 在 src/WifiReceiver 中添加以下代码

package com.example.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

class WifiReceiver extends BroadcastReceiver {
   WifiManager wifiManager;
   StringBuilder sb;
   ListView wifiDeviceList;
   public WifiReceiver(WifiManager wifiManager, ListView wifiDeviceList) {
      this.wifiManager = wifiManager;
      this.wifiDeviceList = wifiDeviceList;
   }
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
            sb = new StringBuilder();
            List<ScanResult> wifiList = wifiManager.getScanResults();
         ArrayList<String> deviceList = new ArrayList<>();
         for (ScanResult scanResult : wifiList) {
            sb.append("
").append(scanResult.SSID).append(" - ").append(scanResult.capabilities);             deviceList.add(scanResult.SSID + " - " + scanResult.capabilities   );          }          Toast.makeText(context, sb, Toast.LENGTH_SHORT).show();          ArrayAdapter arrayAdapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, deviceList.toArray());          wifiDeviceList.setAdapter(arrayAdapter);       }    } }

步骤 5 − 在 androidManifest.xml 中添加以下代码

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
   package = "com.example.myapplication">
   <uses-permission android:name = "android.permission.ACCESS_COARSE_LOCATION" />
   <uses-permission android:name = "android.permission.ACCESS_WIFI_STATE" />
   <uses-permission android:name = "android.permission.CHANGE_WIFI_STATE" />
   <application
      android:allowBackup = "true"
      android:icon = "@mipmap/ic_launcher"
      android:label = "@string/app_name"
      android:roundIcon = "@mipmap/ic_launcher_round"
      android:supportsRtl = "true"
      android:theme = "@style/AppTheme">
      <activity android:name = "com.example.myapplication.MainActivity">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

让我们尝试运行你的应用程序。我假设你的实际 Android 移动设备已连接到你的计算机。要从 Android Studio 运行应用程序,请打开项目的某个活动文件,然后单击工具栏中的运行   图标。选择你的移动设备作为选项,然后检查你的移动设备,它将显示你的默认屏幕 -

点击这里下载项目代码

更新于: 2019 年 7 月 30 日

1 千次浏览

启动你的职业生涯

完成课程,获取认证

入门
广告