我试图从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强度,那么它就不可行了。
答案 0 :(得分:0)
您应该考虑更清晰,更简单的解决方案。 有简单的策略做到这一点。您使用系统ALARM_SERVICE运行服务并在接收时获得您的wifi信号强度,您可以存储触发计数并将警报服务设置为您提到的几倍或五倍。 我相信这篇文章会对你有所帮助。 Scheduling stuff... 这可能会更好article