Android:连续扫描所有AP(接入点)
我对android应用程序开发相当新颖。我正在研究一个android应用程序来ping访问点以访问其RSSI值来估计用户的位置。Android:连续扫描所有AP(接入点)
虽然我目前有这个'工作',但我相信在我的实现中有一个错误会创建太多的“onReceive()”调用。在应用程序的整个生命周期中,对这个函数的调用量都是线性的。
我将要发布的代码的目标是简单地扫描WiFi接入点,获取其RSSI值,然后不断循环。电池寿命不成问题,性能是一个更重要的指标。
MainActivity.java:
Handler handler = new Handler();
final Runnable locationUpdate = new Runnable() {
@Override
public void run() {
getLocation();
//customView.setLocation(getX_pixel(curLocation.getX()), getY_pixel(curLocation.getY()));
//customView.invalidate();
handler.postDelayed(locationUpdate, 1000);
}
};
private void getLocation() {
Context context = getApplicationContext();
WifiScanReceiver wifiReceiver = new WifiScanReceiver();
registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifiManager.startScan();
Log.d("START SCAN CALLED", "");
}
然后在相同的文件中,在onCreate()方法:
handler.post(locationUpdate);
然后,在相同的文件中,onCreate()方法之外:
class WifiScanReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context c, Intent intent) {
WifiManager wifiManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
List<ScanResult> scan = wifiManager.getScanResults();
// Application specific code:
sortScan(scan);
count+= 1;
System.out.println("Count: " + count);
}
}
};
我确认了斜坡/线程问题,因为当程序到达时我递增并输出到控制台“sortScan(扫描)”,您可以清楚地看到结果呈线性上升。
就像我刚才说的那样,我的目的是在第一次扫描完成后立即重新扫描,并在应用程序的整个生命周期中对其进行循环。
任何帮助将不胜感激,谢谢。
您正在重复注册您不需要的接收器。只需在onCreate()中注册WifiScanReceiver一次。然后调用getLocation()函数中的开始扫描。
WifiManager wifiManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
Context context = getApplicationContext();
WifiScanReceiver wifiReceiver = new WifiScanReceiver();
registerReceiver(wifiReceiver, new
IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager =
(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
Handler handler = new Handler();
final Runnable locationUpdate = new Runnable() {
@Override
public void run() {
getLocation();
//This line will continuously call this Runnable with 1000 milliseconds gap
handler.postDelayed(locationUpdate, 1000);
}
};
private void getLocation() {
wifiManager.startScan();
Log.d("START SCAN CALLED", "");
}
}
class WifiScanReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context c, Intent intent) {
if(intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)){
//New scan results are available. Arrange a callback to the activity here.
}
}
}
你不应该在onReceive()中进行繁重的处理。安排一个回调到活动来做到这一点。
您每次运行getLocation()
时都会创建一个新的广播接收器。每个接收者都获得WifiManager.SCAN_RESULTS_AVAILABLE_ACTION
广播。尝试在适当的上下文中分配和注册一次接收机,并且只需拨打startScan()
中的getLocation()
即可。
连续循环扫描WiFi AP的RSSI值的最佳方法是简单地在OnCreate中启动第一次扫描。然后在BroadcastReceiver的onReceive回调中,再次调用开始扫描。