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

时间:2019-04-15 15:02:44

标签: java android android-wifi wifimanager indoor-positioning-system

我正在为我的研究开发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();
}



3 个答案:

答案 0 :(得分:0)

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

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();

}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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