如何获得随时间更新的真实wifi扫描结果

How to get the true wifi scan results updated with the time

我正在为我的研究开发 wifi 室内定位应用程序。我从 https://github.com/Talentica/WifiIndoorPositioning 获得了附加的 wifi 扫描服务和广播接收器 获取 wifi 扫描结果并使用它来获取室内位置。 我的问题是 wifi 扫描结果不会随着时间的推移从一个地方移动到另一个地方而更新,它似乎给出了私有扫描结果而不是新列表。 我如何编辑它以获得随时间推移的实际更新扫描结果

public class WifiService extends Service {

    private final String TAG = "WifiService";
    WifiConfiguration wifiConfiguration = new WifiConfiguration();

    private WifiManager mWifiManager;
    private ScheduledFuture<?> scheduleReaderHandle;
    private ScheduledExecutorService mScheduler;
    private WifiData mWifiData;

    private long initialDelay = 0;
    private long periodReader = AppContants.FETCH_INTERVAL;
    List<ScanResult> mResults;

    /**
     * It creates a new Thread that it is executed periodically reading the last
     * scanning of WiFi networks (if WiFi is available).
     */
    @Override
    public void onCreate() {
        Log.d(TAG, "WifiService onCreate");
        mWifiData = new WifiData();
        mWifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        mScheduler = Executors.newScheduledThreadPool(1);

        scheduleReaderHandle = mScheduler.scheduleAtFixedRate(new ScheduleReader(), initialDelay, periodReader,
                TimeUnit.MILLISECONDS);
          mResults = new ArrayList<ScanResult>() {};


    }


    /**
     * Kills the periodical Thread before destroying the service
     */
    @Override
    public void onDestroy() {
        // stop read thread
        scheduleReaderHandle.cancel(true);
        mScheduler.shutdown();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * Performs a periodical read of the WiFi scan result, then it creates a new
     * {@link WifiData ()} object containing the list of networks and finally it
     * sends it to the main activity for being displayed.
     */
    class ScheduleReader implements Runnable {
        @Override
        public void run() {

            if (mWifiManager.isWifiEnabled()) {

                mResults = mWifiManager.getScanResults();


                Log.d(TAG, "New scan result: (" + mResults.size() + ") networks found");
                // store networks
                mWifiData.addNetworks(mResults);
                // send data to UI
                Intent intent = new Intent(AppContants.INTENT_FILTER);
                intent.putExtra(AppContants.WIFI_DATA, mWifiData);
                LocalBroadcastManager.getInstance(WifiService.this).sendBroadcast(intent);
                mResults.clear();

            }
        }
    }
}
  public class MainActivityReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            NumberFormat formatter = new DecimalFormat("#0.0000");
            mWifiData = (WifiData) intent.getParcelableExtra(AppContants.WIFI_DATA);

            if (mWifiData.getNetworks().size() != 0) {


               List<WifiDataNetwork> latestScanList = mWifiData.getNetworks();
                LocationWithNearbyPlaces loc = AlgorithmTxtDb.processingAlgorithms(fingerprintRefPointsList, routersList, latestScanList, 2);
}
} 

public class MainActivityReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            NumberFormat formatter = new DecimalFormat("#0.0000");
            mWifiData = (WifiData) intent.getParcelableExtra(AppContants.WIFI_DATA);

            if (mWifiData.getNetworks().size() != 0) {



                List<WifiDataNetwork> latestScanList = mWifiData.getNetworks();
                LocationWithNearbyPlaces loc = AlgorithmTxtDb.processingAlgorithms(fingerprintRefPointsList, routersList, latestScanList, 2);

                }
            }

        }

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    mWifiData = null;
        // set receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(AppContants.INTENT_FILTER));
        // launch WiFi service
        wifiServiceIntent = new Intent(this, WifiService.class);
        startService(wifiServiceIntent);
        // recover retained object
        mWifiData = (WifiData) getLastNonConfigurationInstance();
}



在您的应用中添加以下依赖项。

implementation 'com.easyconnectlibrary.library:easyconnectlibrary:1.0.5'

使用下面的代码每 10 秒获取一次 wifi 扫描结果。但是,您可以根据需要将 10 秒更改为 5 秒。

private WifiConnection mWifiConnection;
private Handler mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWifiConnection = WifiConnection.getInstance(this);
    mWifiConnection.registerWifiScanListener(new WifiScanListener() {
        @Override
        public void onWifiScanList(List<ScanResult> scanResultList) {
            int i = 1;
            if (scanResultList.size() == 0) {
                Log.i("MainActivity Result " + i, "No Wifi available");
            } else {
                for (ScanResult scanResult : scanResultList) {
                    Log.i("MainActivity Result " + i, scanResult.SSID);
                    i++;
                }
            }
        }

        @Override
        public void onLocationServiceOff() {
            Log.i("MainActivity", "Location service should be turned on");
        }

        @Override
        public void onError(WIFI_SCAN_ERROR wifi_scan_error) {
            Log.i("MainActivity", wifi_scan_error + " Error");
        }
    });
    mHandler = new Handler();
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Log.i("MainActivity", "Handler Started");
            mWifiConnection.getWifiScanList();

        }
    };
    new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                mHandler.post(runnable);
                try {
                     //sleep for 10 second before making another scan request
                    Thread.sleep(10000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();

}

问题来自android 9.0 android 的最新版本(android 9 (Pie))对 WIFI 扫描有新的限制,如 android 所记录。他们为前台和后台场景的扫描间隔添加了节流以节省功耗。 Android 9 及更高版本:每个前台应用程序可以在 2 分钟内扫描四次。这允许在短时间内进行突发扫描。所有后台应用加起来可以在 30 分钟内扫描一次。 android wifi scan 以下链接表示此节流的响应: links represent the response of this throttling, link 2, link 3, link 4

某个应用在特定时间段内请求扫描次数过多。这可能会导致额外的 通过前台和后台应用程序的“扫描限制”拒绝扫描请求。 注:持有android.Manifest.permission.NETWORK_SETTINGS权限的应用免除 来自扫描限制。

   <uses-permission android:name="android.Manifest.permission.NETWORK_SETTINGS"></uses-permission>