每次按下按钮,如何在Android手机中收到新的扫描结果?

时间:2016-05-26 01:35:09

标签: android android-wifi wifimanager

我正在创建一个需要扫描周围访问点的应用程序,并根据结果进行一些计算。到目前为止,我确信WifiManager.statScan()方法虽然启动了新的扫描,但它并不会自动返回新扫描的结果。

这是我的代码:

public void onClick(View v) {
    switch (v.getId()){
        case R.id.button:
            //do some reseting for the GUI and the values of the problem.
            break;
        case R.id.button2:
            wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wifiManager.startScan();
            List<ScanResult> scanResult = null;
            if(wifiManager.startScan()){
                scanResult = wifiManager.getScanResults();
            }
            // Do the calculations.
            break;

    }
}

我的问题是我不确定是否使用此代码我实际上是从启动扫描得到的结果或来自先前扫描的结果,如果后者是正确的,我怎样才能从新扫描得到结果?

非常感谢。

在搜索和阅读各种帖子和tutorias后,我的代码转换如下:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
BroadcastReceiver receiver;
private List<ScanResult> scanResult;
boolean waiting;
// and other irrelevant variables.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //initialization of the elements of the GUI
    reset.setOnClickListener(this);
    locate.setOnClickListener(this);
    wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    waiting = true;
    receiver = new WifiScaner(this);
    registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.button:
            // resetting the variables of the application
            break;
        case R.id.button2:
            wifiManager.startScan();
            while (waiting)  {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Log.d("PROJECT1","Wifi WAITING");
            }
            //Calculations
            break;

    }
}

public class WifiScaner extends BroadcastReceiver{
    MainActivity main;
    public WifiScaner(MainActivity main){
        super();
        this.main = main;
    }
    public void onReceive(Context c, Intent intent) {
        scanResult = main.wifiManager.getScanResults();
        waiting = false;
        Log.d("PROJECT1","Wifi RECEIVED");
    }
}

} 但由于某种原因,似乎我从未进入WifiScaner的onReceive。任何线索为什么会发生这种情况?

1 个答案:

答案 0 :(得分:1)

你是对的,扫描需要一些时间,因此无法立即获得结果。这可以通过startScan()方法的文档确认:

&#34;请求扫描接入点。立即返回。稍后通过在扫描完成时发送的异步事件来了解结果的可用性。&#34;

以下链接似乎有一个很好的示例,说明扫描完成后如何通知:http://www.tutorialspoint.com/android/android_wi_fi.htm