我正在尝试从 wifi 中找到信号强度。我想采集 5 个信号强度样本。所以,我保留了一个计时器,它可以帮助我让代码每秒运行一次。我编写的代码如下所示。
我得到的输出是:被称为 0
被叫 1
被叫 2
被叫 3
被叫 4
我没有得到 sb(我使用的字符串生成器)值。
如果我从 onreceive 中删除内容并将其保留在方法之外,我会得到信号强度值。但它并不是每秒都在更新。
public class MainActivity extends Activity {
protected static final long TIME_DELAY = 1000;
TextView mTextView;
Handler handler=new Handler();
int count =0; String data ="";
private static final IntentFilter FILTER = new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text_id);
handler.post(updateTextRunnable);
}
Runnable updateTextRunnable = new Runnable() {
public void run() {
if (count < 5) {
final StringBuilder sb = new StringBuilder();
final WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
class WifiScanReceiver extends BroadcastReceiver {
//BroadcastReceiver WifiScanReceiver = new BroadcastReceiver() {
public void onReceive(Context c, Intent intent) {
List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
for (ScanResult result : wifiScanList) {
if (result.SSID.equals("DAL-WPA2")) {
sb.append(""+result.level);
}
if (result.SSID.equals("DAL")) {
sb.append(""+result.level);
}
if (result.SSID.equals("eduroam")) {
sb.append(""+result.level);
}
}
}
}
WifiScanReceiver wifiReciever = new WifiScanReceiver();
registerReceiver(wifiReciever, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mTextView.setText("getting called " +count + sb);
count++;
} else {
}
//----------------code here to send values to java server---
handler.postDelayed(this, TIME_DELAY);
}
};
我曾想过使用 onPause 和 onResume 方法,但我认为如果我需要每 1-2 秒更新一次代码以获得新的 wifi 强度,那将是不可行的。