2

我想显示可用 Wifi 设备的列表。这是我的代码,我不明白这里有什么错误:

wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false)
   {
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled",Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
   }   
String[] str1 = null;
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1,str1);
 lv.setAdapter(adapter);
 WifiInfo info = wifi.getConnectionInfo();
textStatus.append("\n\nWiFi Status: " + info.toString());
 boolean b=wifi.isWifiEnabled();
if(b){
 wifi.setWifiEnabled(false);
Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show();
enter code here

这是我的代码,我想通过编程方式专门在 Android 中获取启用 Wifi 的设备属性。我怎么能得到那个?

 public void onReceive(Context c, Intent intent) 
 {
 results = wifi.getScanResults();
 size = results.size();
 int i = 0;
 str1 = new String[size];
 for (ScanResult result : results){
 str1[i] = result.SSID + " " + result.level;
 i++;
 }
4

3 回答 3

7

您可以通过以下方式获取可用的 WIFI 扫描结果

List<ScanResult> mScanResults = mWifiManager.getScanResults();

然后迭代mScanResults并使用results.SSID. 此外,如果您有兴趣获得可WifiManager.compareSignalLevel(int rssiA, int rssiB)用于比较两个网络的最佳网络。

ScanResult bestResult = null;
for(ScanResult results : mScanResults){
   Log.d("result",results.SSID);
   if(bestResult == null || WifiManager.compareSignalLevel(bestResult.level,
                                                         results.level) < 0){
      bestResult = results;
   }
}
String message = String.format("%s networks found. %s is the strongest.", 
                                           mScanResults.size(), bestResult.SSID);
Log.d("best network",message);

您可以从我的repository.

于 2012-08-10T09:05:04.543 回答
1

试试这个代码。

import java.util.ArrayList;
import java.util.HashMap;    
import java.util.List;    
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;    
import android.content.Intent;     
import android.content.IntentFilter;    
import android.net.wifi.ScanResult;    
import android.net.wifi.WifiConfiguration;   
import android.net.wifi.WifiManager;    
import android.os.Bundle;    
import android.util.Log;   
import android.view.View;    
import android.view.View.OnClickListener;    
import android.widget.AdapterView;    
import android.widget.Button;    
import android.widget.ListView;    
import android.widget.SimpleAdapter;    
import android.widget.TextView;    
import android.widget.Toast;

public class WiFiDemo extends Activity implements OnClickListener
 {      
    WifiManager wifi;       
    ListView lv;
    TextView textStatus;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;

    String ITEM_KEY = "key";
    ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
    SimpleAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        textStatus = (TextView) findViewById(R.id.textStatus);
        buttonScan = (Button) findViewById(R.id.buttonScan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.list);

        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }   
        this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
        lv.setAdapter(this.adapter);

        registerReceiver(new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context c, Intent intent) 
            {
               results = wifi.getScanResults();
               size = results.size();
            }
        }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));                    
    }

    public void onClick(View view) 
    {
        arraylist.clear();          
        wifi.startScan();

        Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
        try 
        {
            size = size - 1;
            while (size >= 0) 
            {   
                HashMap<String, String> item = new HashMap<String, String>();                       
                item.put(ITEM_KEY, results.get(size).SSID + "  " + results.get(size).capabilities);

                arraylist.add(item);
                size--;
                adapter.notifyDataSetChanged();                 
            } 
        }
        catch (Exception e)
        { }         
    }    
}
于 2012-08-10T09:04:43.327 回答
1

基于 android 开发者网站,搜索 wifi 列表的最佳方法如下:

WifiManager wifiManager = (WifiManager)
                   context.getSystemService(Context.WIFI_SERVICE);

BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context c, Intent intent) {
    boolean success = intent.getBooleanExtra(
                       WifiManager.EXTRA_RESULTS_UPDATED, false);
    if (success) {
      scanSuccess();
    } else {
      // scan failure handling
      scanFailure();
    }
  }
};

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
context.registerReceiver(wifiScanReceiver, intentFilter);

boolean success = wifiManager.startScan();
if (!success) {
  // scan failure handling
  scanFailure();
}

....

private void scanSuccess() {
  List<ScanResult> results = wifiManager.getScanResults();
  ... use new scan results ...
}

private void scanFailure() {
  // handle failure: new scan did NOT succeed
  // consider using old scan results: these are the OLD results!
  List<ScanResult> results = wifiManager.getScanResults();
  ... potentially use older scan results ...
}

安卓 8.0 和安卓 8.1:

成功调用 WifiManager.getScanResults() 需要以下任一权限:

  • ACCESS_FINE_LOCATION

  • ACCESS_COARSE_LOCATION

  • CHANGE_WIFI_STATE

如果调用应用程序没有任何这些权限,则调用将失败并出现 SecurityException。

或者,在运行 Android 8.0(API 级别 26)及更高版本的设备上,您可以使用 CompanionDeviceManager 代表您的应用执行附近配套设备的扫描,而无需位置权限。

来源:https ://developer.android.com/guide/topics/connectivity/wifi-scan

于 2020-12-09T12:22:26.670 回答