首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Wifimanager.getConfiguredNetworks()返回null

Wifimanager.getConfiguredNetworks()返回null
EN

Stack Overflow用户
提问于 2017-05-15 20:09:50
回答 2查看 5.2K关注 0票数 2

我在网上学习了一些教程,试图在android上创建一个wifi扫描仪,但是我在WifiManager的getConfiguredNetworks()方法上遇到了麻烦。它经常返回null,而不是预期的列表。

我在网上做了一些搜索,我的代码似乎一直在抛出一个RemoteException。即使在阅读了关于:http://docs.oracle.com/javase/7/docs/api/java/rmi/RemoteException.html的文档之后,我仍然不了解RemoteExcecption是什么或如何解决它。

下面是我的代码片段:

代码语言:javascript
运行
AI代码解释
复制
    wifi=(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifi.setWifiEnabled(true);
    Log.d("WifiInfo", "info is: " + info);

    //  list available network

    List<WifiConfiguration> configurations = wifi.getConfiguredNetworks(); //configurations is null
    Log.d("List<WifiConfig>", "configurations is: " + configurations); //error thrown here
    // Is WiFi on?
    if (wifi.isWifiEnabled()) {
        // Check for existing APs.
        for(WifiConfiguration config : configurations) {
            Log.d("CONFIG", config.toString());
            myItems.add(config.toString());
        }
    }

有人能帮我吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-15 20:16:29

用这个代码..。

代码语言:javascript
运行
AI代码解释
复制
public class MainActivity extends AppCompatActivity 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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


       // textStatus = (TextView) findViewById(R.id.test1);
        buttonScan = (Button) findViewById(R.id.btn);
        buttonScan.setOnClickListener(MainActivity.this);
        lv = (ListView) findViewById(R.id.listview_item);

        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(MainActivity.this, arraylist, R.layout.raw, new String[]{ITEM_KEY}, new int[]{R.id.row});
        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));


        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, arraylist.get(position).toString(), Toast.LENGTH_SHORT).show();

                connectToAP(arraylist.get(position).get("key"), "");

            }
        });
    }

    public void connectToAP(String ssid, final String passkey) {


        final WifiConfiguration wifiConfiguration = new WifiConfiguration();

        final String networkSSID = ssid;
        final String[] networkPass = {passkey};
        final String[] password = {""};
        for (ScanResult result : results) {
            if (result.SSID.equals(networkSSID)) {

                String securityMode = getScanResultSecurity(result);

                if (securityMode.equals("PSK")) {
                    final AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                    dialog.setTitle("Password");
                    dialog.setMessage("Enter Passsword");
                    final EditText editText = new EditText(MainActivity.this);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
                    editText.setLayoutParams(lp);
                    dialog.setView(editText);


                    dialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            password[0] = editText.getText().toString();
                            wifiConfiguration.SSID = "\"" + networkSSID + "\"";
                            wifiConfiguration.preSharedKey = "\"" + editText.getText().toString() + "\"";
                            wifiConfiguration.hiddenSSID = true;
                            wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
                            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                            wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                            wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                            wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                            wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

                            int res = wifi.addNetwork(wifiConfiguration);

                            wifi.enableNetwork(res, true);

                            boolean changeHappen = wifi.saveConfiguration();

                            if (res != -1 && changeHappen) {

                                // .connectedSsidName = networkSSID;

                            } else {
                                // Log.d(TAG, "*** Change NOT happen");
                            }

                            wifi.setWifiEnabled(true);

                        }
                    });

                    dialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
                    dialog.show();

                }

                if (securityMode.equalsIgnoreCase("OPEN")) {

                    wifiConfiguration.SSID = "\"" + networkSSID + "\"";
                    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                    int res = wifi.addNetwork(wifiConfiguration);
                    boolean b = wifi.enableNetwork(res, true);
                    wifi.setWifiEnabled(true);

                } else if (securityMode.equalsIgnoreCase("WEP")) {

                    wifiConfiguration.SSID = "\"" + networkSSID + "\"";
                    wifiConfiguration.wepKeys[0] = "\"" + password[0] + "\"";
                    wifiConfiguration.wepTxKeyIndex = 0;
                    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                    wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                    int res = wifi.addNetwork(wifiConfiguration);

                    boolean b = wifi.enableNetwork(res, true);

                    wifi.setWifiEnabled(true);
                }


            }
        }
    }

    public String getScanResultSecurity(ScanResult scanResult) {

        final String cap = scanResult.capabilities;
        final String[] securityModes = {"WEP", "PSK", "EAP"};

        for (int i = securityModes.length - 1; i >= 0; i--) {
            if (cap.contains(securityModes[i])) {
                return securityModes[i];
            }
        }

        return "OPEN";


    }

    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);
                item.put("capablity", results.get(size).capabilities);
                adapter.notifyDataSetChanged();

                arraylist.add(item);
                size--;
            }
        } catch (Exception e) {
        }
    }
}

activity_main.xml

代码语言:javascript
运行
AI代码解释
复制
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.admin.wifi.MainActivity">



    <ListView
        android:id="@+id/listview_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


    </ListView>
    <Button
        android:id="@+id/btn"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="scan" />


</RelativeLayout>

raw.xml

代码语言:javascript
运行
AI代码解释
复制
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:id="@+id/row"
        android:layout_height="wrap_content" />

</LinearLayout>

少女节

票数 1
EN

Stack Overflow用户

发布于 2020-10-29 07:19:51

我刚才也是这样的。首先:在关闭wifi时,getConfiguredNetworks()总是返回null。而且,WifiService在setWifiEnabled(true)getConfiguredNetworks()之间似乎需要一点时间。我创建了一个小循环,只打印了一个日志:

代码语言:javascript
运行
AI代码解释
复制
    wifiMgr.setWifiEnabled(true); // else we won't be able to read the networks
    while (wifiMgr.getWifiState() != WIFI_STATE_ENABLED) {
      LogIf.d("FOO", "waiting for wifi-system to provide network-data");
    }
    for (WifiConfiguration cfg : wifiMgr.getConfiguredNetworks()) {
      ..

在打开WifiService之前,最好使用Handler来签入。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43992344

复制
相关文章
nginx配置Symfony
server { listen 80; server_name blog.phpfs.com; root /data/web; rewrite ^/a
苦咖啡
2018/04/28
1.7K0
Symfony是什么
众所周知前面有说到PHP的七大框架,接下来就来说说Symfony框架,希望说的对大家有所帮助。
叫我可儿呀
2019/11/26
2.2K0
Symfony是什么
Symfony 服务容器入门
本文是依赖注入(Depeendency Injection)系列教程的第 3 篇文章,本系列教程主要讲解如何使用 PHP 实现一个轻量级服务容器,教程包括:
柳公子
2018/09/17
3.4K0
Symfony 3 框架+Elasticsearch
目录src/AppBundle/Controller/SearchController.php
Stanley Sun
2019/09/23
7990
Ubuntu配置Symfony环境
1、装好ubuntu使用 sudo passwd root 设置root密码 2、安装ssh sudo apt-get install openssh-server 3、ssh连接进行安装LAMP环境 启动ssh服务 /etc/init.d/ssh start 4、修改ssh连接乱码 进入系统后 sudo vim /etc/environment LANG=”zh_CN.UTF-8″ LANGUAGE=”zh_CN:zh” 修改为 LANG=”en_GB.UTF-8″ LANGUAGE=”en_US:en”
苦咖啡
2018/05/07
2K0
php使用Symfony EventDispatcher 组件
大家好,这篇文章将通过我在实际开发工作中的例子,来介绍Symfony的EventDispatcher组件的使用及实现原理。
OwenZhang
2021/12/08
2.1K0
Symfony 服务容器性能优化
本文是依赖注入(Depeendency Injection)系列教程的最后一篇文章,本系列教程主要讲解如何使用 PHP 实现一个轻量级服务容器,教程包括:
柳公子
2018/09/17
3.2K0
Symfony 服务容器性能优化
撸个 symfony4(一)
最近在看symfony,发现laravel里面也引用了这个框架,国内关于symfony的资料不是很多,但是体验了以下之后,感觉还是不错的,所以记录下踩坑之旅。这是[官方文档](https://symfony.com)
仇诺伊
2020/04/24
4640
撸个 symfony4(一)
撸个 symfony4(二)
目标其实是完成如下的需求,如果有想看源码的,可以看下sf官网出的一个demo。
仇诺伊
2020/04/24
2.5K0
撸个 symfony4(二)
关于symfony的serivce存在的意义
最近硬着头皮改了一个symfony的serivce 。 改完之后突然理解了symonfy启用service 的良苦用心。
lilugirl
2019/05/26
7140
有了这款神器,人人都是作曲家!
摘要:人工智能作曲APP Amper Music的简单介绍和测评,以及人工智能和机器学习的小科普
生信宝典
2019/10/15
5.5K0
基于 Symfony 组件封装 HTTP 请求响应类
上篇教程学院君给大家介绍了命名空间以及如何基于 Composer 来管理命名空间与 PHP 脚本路径的映射,自此以后,我们将基于这套机制来实现 PHP 类的自动加载和函数引入。
学院君
2020/08/18
8.7K0
基于 Symfony 组件封装 HTTP 请求响应类
Symfony 服务容器:使用建造者创建服务
本文是依赖注入(Depeendency Injection)系列教程的第 5 篇文章,本系列教程主要讲解如何使用 PHP 实现一个轻量级服务容器,教程包括:
柳公子
2018/09/17
2.6K0
Yahoo 书签系统使用 Php 语言的 symfony 框架
根据Yahoo 技术工程师 Michael Salisbury  介绍,Yahoo 书签使用 symfony 框架开发完成,他们选择 symfony 的理由如下:
田春峰-JCJC错别字检测
2019/02/14
1K0
如何提高编程能力?
其实很多人学编程都会遇到困难,我觉得其中一个根本原因是他们没搞明白学编程到底是学什么。
Daotin
2018/08/31
5930
Symfony 服务容器:使用 XML 或 YAML 文件描述服务
本文是依赖注入(Depeendency Injection)系列教程的第 5 篇文章,本系列教程主要讲解如何使用 PHP 实现一个轻量级服务容器,教程包括:
柳公子
2018/09/17
1.8K0
使用Symfony的Console组件构建命令行程序
我们新开设一门视频课程《构建命令行程序》。主要讲解如何使用symfony的console组件,构建命令行应用。在我们的印象中,php程序大部分是通过浏览器执行(即web应用)。在命令终端执行的应用,相对比较少。使用Laravel后,我们最常用的操作有: 创建数据库的migration文件 php artisan make:migration 创建模型文件 php artisan make:model 创建控制器文件 php artisan make:controller 开设这门课程的目标,是为Lara
企鹅号小编
2018/01/15
2K0
使用Symfony的Console组件构建命令行程序
谷歌首个AI版Doodle:向伟大作曲家巴赫致敬
3 月 21 日是著名音乐家约翰·塞巴斯蒂安·巴赫的生日,谷歌决定以一种特殊的方式向他致敬:让人人都能以巴赫的风格创作自己的乐曲。 通过机器学习算法,谷歌开发了 Coconet 多功能模型,可以让你用巴赫的风格演奏自己写下的乐谱。你也可以通过这个小工具来体验 AI 算法如何将一些我们熟悉的旋律「巴赫化」,亦或你和巴赫「合作」的乐曲将呈现出怎样更加现代摇滚的曲风。
机器之心
2019/04/29
7180
谷歌首个AI版Doodle:向伟大作曲家巴赫致敬
二叉树:总结篇!(需要掌握的二叉树技能都在这里了)
不知不觉二叉树已经和我们度过了「三十三天」,代码随想录里已经发了「三十三篇二叉树的文章」,详细讲解了「30+二叉树经典题目」,一直坚持下来的录友们一定会二叉树有深刻理解了。
代码随想录
2020/10/30
8390
二叉树:总结篇!(需要掌握的二叉树技能都在这里了)
哎,记者、设计师、作曲家……你们的饭碗还稳吗?
企鹅号小编
2017/12/28
9280
哎,记者、设计师、作曲家……你们的饭碗还稳吗?

相似问题

安装Symfony,作曲家

10

InvalidArgumentException作曲家安装symfony

34

symfony flex作曲家InvalidArgumentException

118

Symfony 2 ->作曲家和CloudControl

36

作曲家没有要求symfony/symfony在symfony 4上

12
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文