2014-06-23 63 views
0

我有一個關於在我的應用程序中使用WiFiManger的問題。 的代碼很簡單,我已經創造了這個服務,它可以掃描網絡以獲取可用的無線網絡:等到startScan完成掃描

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    mapName = intent.getExtras().getString("mapName"); 
    sendNotification(); 
    mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); 

    // Check for wifi is disabled 
    if (!mainWifi.isWifiEnabled()) { 
     // If wifi disabled then enable it 
     Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", 
       Toast.LENGTH_LONG).show(); 

     mainWifi.setWifiEnabled(true); 
    } 
    mainWifi.startScan(); 
    List<ScanResult> scanResults=mainWifi.getScanResults(); 
    readAps=getAps(scanResults); 
    //List of AP received in current position 
    String result=compareRP(); 
    if(!result.isEmpty()) 
     Toast.makeText(this, "Localized in RP: "+result, Toast.LENGTH_LONG).show(); 
    else 
     Toast.makeText(this, "Unable to localize you in this map", Toast.LENGTH_LONG).show(); 
    return START_NOT_STICKY; 
} 

private ArrayList<AccessPoint> getAps(List<ScanResult> scanResults) { 
    ArrayList<AccessPoint> temp = new ArrayList<AccessPoint>(); 
    for(ScanResult s:scanResults){ 
     temp.add(new AccessPoint(s.SSID,s.level,s.frequency)); 
    } 
    return temp; 
} 

如何添加此條件:我想等待一個「新鮮」無線網絡列表中,那出現時:

mainwifi.startScan(); 

方法返回。

現在我的服務仍然繼續與羣集匹配算法,我不希望它。我該怎麼做?

感謝您的幫助!

弗雷德

+0

註冊到廣播,你將有無線列表。你不能等。 –

+0

我試圖用BroadcastReceiver解決它,但它不工作...對於集羣匹配我需要一個完整的列表來做比較,所以我要等到mainWifi.startScan()方法返回我「真正」。 (這裏是BroadcastReceiver的代碼示例:http://pastebin.com/RxV2XFEi) – Stiva

+1

您應該實現一個廣播,它將監聽SCAN_RESULTS_AVAILABLE_ACTION。當掃描準備好時,它由Android觸發。 startScan用於開始掃描並返回true/false以通知您是否開始搜索。您不能等到掃描完成。您應該將您的應用程序邏輯移入廣播的onReceive內部。 –

回答

0

你必須使用一個BroadcastReceiver您的活動中。

private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context c, Intent intent) { 
     // This condition is not necessary if you listen to only one action 
     if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { 
      List<ScanResult> mScanResults = mWifiManager.getScanResults(); 
      Toast.makeText(getApplicationContext(), "Scan results are available", Toast.LENGTH_LONG).show(); 
      // Do what you want 
     } 
    } 
}; 

private WifiManager mWifiManager; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); 

    IntentFilter intentFilter = new IntentFilter(); 
    intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 
    // You can add multiple actions... 
    registerReceiver(mWifiScanReceiver, intentFilter); 
    // ... 
    mWifiManager.startScan(); 

}