其他分享
首页 > 其他分享> > Android WifiManager :: getScanResults()仍返回空列表

Android WifiManager :: getScanResults()仍返回空列表

作者:互联网

作为Android编程的新手,我试图使用WifiManager的getScanResults()方法获取SSID列表,但是即使我已授予它ACCESS_COARSE_LOCATION权限以及CHANGE_WIFI_STATE(对于startScan()方法),该列表仍为空,无论是在清单中还是在运行时检查/请求它.

在SCAN_RESULTS_AVAILABLE_ACTION的广播接收器中,我什至使用键EXTRA_RESULTS_UPDATED检查了意图的额外字段,结果返回true.

但是,list.size()始终返回0.

我在这里想念什么?我正在Android 7.0 API 24设备上进行测试.

编辑:代码如下:

MainActivity.java:

public class MainActivity extends Activity implements View.OnClickListener {
    private static final String TAG="WiFiDemo";

    WifiManager wifiManager;
    WifiBroadcastReceiver wifiReceiver;

    TextView textView;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        Log.d(TAG, "onCreate()");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Check for permissions
        if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED)
            || (ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE)
                    != PackageManager.PERMISSION_GRANTED))
        {
            Log.d(TAG, "Requesting permissions");

            //Request permission
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                                 Manifest.permission.ACCESS_FINE_LOCATION,
                                 Manifest.permission.ACCESS_WIFI_STATE,
                                 Manifest.permission.CHANGE_WIFI_STATE,
                                 Manifest.permission.ACCESS_NETWORK_STATE},
                    123);
        }
        else
            Log.d(TAG, "Permissions already granted");

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

        textView = findViewById(R.id.text);
        textView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);

        btn = findViewById(R.id.btn);
        btn.setOnClickListener(this);

        //Instantiate broadcast receiver
        wifiReceiver = new WifiBroadcastReceiver();

        //Register the receiver
        registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
    {
        Log.d(TAG, "onRequestPermissionsResult");

        switch (requestCode)
        {
            case 123:
            {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    // permission was granted
                    Log.d(TAG, "permission granted: " + permissions[0]);
                }
                else
                {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Log.d(TAG, "permission denied: " + permissions[0]);
                }

                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request.
        }
    }

    //Define class to listen to broadcasts
    class WifiBroadcastReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            Log.d(TAG, "onReceive()");
            Toast.makeText(getApplicationContext(), "Scan complete!", Toast.LENGTH_SHORT).show();

            boolean ok = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);

            if (ok)
            {
                Log.d(TAG, "scan OK");

                //StringBuffer buffer = new StringBuffer();
                List<ScanResult> list = wifiManager.getScanResults();

                Toast.makeText(getApplicationContext(), Integer.toString(list.size()), Toast.LENGTH_SHORT).show();

                for (ScanResult scanResult : list)
                {
                    //buffer.append(scanResult);
                    textView.append(scanResult.toString());
                }
            }
            else
                Log.d(TAG, "scan not OK");
        }
    }

    @Override
    protected void onStop()
    {
        // TODO Auto-generated method stub
        unregisterReceiver(wifiReceiver);
        super.onStop();
    }

    @Override
    public void onClick(View view)
    {
        // TODO Auto-generated method stub
        //Toast.makeText(getApplicationContext(), "All Network seached !!",0).show();
        if(view.getId()==R.id.btn)
        {
            Log.d(TAG, "onCreate() wifi.startScan()");

            //if (!wifiManager.isWifiEnabled())
            //    wifiManager.setWifiEnabled(true);

            wifiManager.startScan();
        }
    }
}

在清单中:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.wifi2ir.umagi.wifitest2">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>

解决方法:

从Android 6开始,您必须启用定位服务才能获得所需的结果.授予权限只是完成的一半.

您还可以触发将用户重定向到此设置的意图:

Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);

位置服务是必需的,因为当您访问扫描结果时,您可以访问诸如BSSID(访问点的地址)之类的信息.此信息还可用于检测设备的位置.通过要求位置服务,操作系统可确保用户在使用您的应用程序时了解其位置信息正在被访问.

标签:wifimanager,android
来源: https://codeday.me/bug/20191109/2011373.html