2017-08-22 67 views
-1

我正在構建我的Android Nougat的代碼。掃描WiFi列表返回0在Android nougat

我已經給出了清單文件中的位置和WiFi權限,但是仍然從wlan_Manager.getScanResults()獲得「0」。

我的代碼段是

wlan_Manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
    wlan_switch = (Switch)findViewById(R.id.switch1); 
    list = (ListView)findViewById(R.id.listview); 

wlan_switch.setChecked(wlan_Manager.isWifiEnabled()); 

wifi_list = new ArrayList<>(); 

adapter = new Adapter(this,R.layout.default_listview,wifi_list); 
list.setAdapter(adapter); 
wifireceiver = new wifi_Receiver(adapter,wifi_list); 

registerReceiver(wifireceiver,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); 

public void onClick(View view) { 
    Log.d("switch", "onClick: "); 
    if (wlan_switch.isChecked() && !wlan_Manager.isWifiEnabled()) 
    { 
     Log.d(TAG, "true: "); 
     wlan_Manager.setWifiEnabled(true); 
     wifi_list.clear(); 

     wlan_Manager.startScan(); 
    } 
    else { 
     Log.d(TAG, "false "); 
     wlan_Manager.setWifiEnabled(false); 
     wifi_list.clear(); 
     adapter.clear(); 
    } 
} 

@Override 
    public void onReceive(Context context, Intent intent) 
    { 
      int size =0 ; 
      //scan_Result.clear(); 
      Log.d("WifScanner", "onReceive"); 
      wlan_Manager = (WifiManager)context.getApplicationContext().getSystemService(context.WIFI_SERVICE); 
      scan_Result = wlan_Manager.getScanResults(); 
      size = scan_Result.size(); 

      Log.d(TAG, "onReceive: " + size); 

      while (size > 0) 
      { 
       Log.d(TAG, "size : "+size); 
       size--; 
       wifi_list.add(scan_Result.get(size).SSID); 
       adapter.notifyDataSetChanged(); 
      } 
    } 

但是,當我爲較低的Android版本構建代碼時,它顯示WiFi列表。

+0

<使用權限android:name =「android.permission.CHANGE_WIFI_STATE」/> <使用權限android:name =「android.permission.ACCESS_FINE_LOCATION 「/> <使用權限android:name =」android.permission.ACCESS_COARSE_LOCATION「/> – abhishek

回答

0

您在開始任何掃描之前調用getScanResults()。 爲了您的使用情況,你需要開始無線掃描與startScan() - 方法並註冊一個BroadcastReceiver該過濾器與動作意圖:

WifiManager.SCAN_RESULTS_AVAILABLE_ACTION 

在這裏你可以找到一些示例代碼: Android Wifi Scan - BroadcastReceiver for SCAN_RESULTS_AVAILABLE_ACTION not getting called

+0

我也用過。 – abhishek

+0

@Override public void onReceive(Context context,Intent intent) int size = 0; wlan_Manager =(WifiManager)context.getApplicationContext()。getSystemService(context.WIFI_SERVICE); scan_Result = wlan_Manager.getScanResults(); size = scan_Result.size(); Log.d(TAG,「onReceive:」+ size); (size> 0) { size--; wifi_list.add(scan_Result.get(size).SSID); adapter.notifyDataSetChanged(); } } – abhishek