Wifi扫描仪无法使用android nougat(7.0)

时间:2017-04-27 09:22:17

标签: java android android-7.0-nougat

我想在wifi开启时扫描所有wifi,但它不能与Android 7.0一起工作,我只有这款手机进行测试(我认为这是一个Android版本的问题)。

如何解决问题?

代码:

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.WifiManager;
import android.os.Bundle; 
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;



public class DetectWifi extends Activity implements View.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.detectwifi_page);

    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(DetectWifi.this, arraylist, R.layout.dialog_wifi, 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)
    { }
 }
}

非常感谢。

2 个答案:

答案 0 :(得分:1)

对于Android 7,需要权限ACCESS_COARSE_LOCATION和ACCESS_FINE_LOCATION来获取Wi-Fi扫描结果。您还必须在设备上打开位置。

答案 1 :(得分:1)

除启用WiFi外,您还必须启用位置服务才能访问扫描结果。如果您只启用了WiFi,则会获得一个空的扫描结果列表。