草庐IT

java - 如何在 Android 中一次又一次地从 wifi 列表中选择相同的 wifi 运营商?

coder 2023-12-15 原文

在我的项目中,我有一个 map 。首先,我转到 Wifi 路由器位置,我扫描 wifi 列表并选择 Operator2 并标记它。接下来我去另一个位置收集相同的以前的 Operator2 详细信息(不要),然后我换个位置再重复一遍。

我可以第一次选择 Wifi 运营商。下次我不知道如何锁定特定的先前选择的运营商详细信息并再次获取运营商详细信息。所以请帮我解决这个问题。

我的代码:

public class WifiReceiver extends BroadcastReceiver {

private WifiManager wifiManager;
private PlanMapperActivity viewerActivity;
private Context newContext;

private String operator;
private String macAddress;
private int signalStrength;
private String wifiMode;
private int frequency;
private String htMode;
private String security;
private int channelNumber;



private AlertDialog wifiAlertDialog;
private ListView  wifiListView;
private ProgressDialog progress;

private Boolean checkWifiSelected;
private Boolean checkServayStart;

private String operatorName;

List<ScanResult> wifiSRList;

private static final String WPA2 = "WPA2";
private static final String WEP = "WEP";
private static final String EAP = "EAP";
private static final String STORED_OPERATOR = "com.kenturf.wifiheatmap.SELECTED_OPERATOR";

private int requiredLevel;
private int ssidCount;

public WifiReceiver(Context ctx,PlanMapperActivity planMapper) {
    this.viewerActivity = planMapper;
    this.newContext = ctx;
}

public WifiReceiver(WifiManager myWifiManager,ProgressDialog wifiProgress,Boolean isWifiSelected,Boolean isSurveyStart) {
    this.wifiManager = myWifiManager;
    this.progress = wifiProgress;
    this.checkWifiSelected = isWifiSelected;
    this.checkServayStart = isSurveyStart;
}

@Override
public void onReceive(final Context context, Intent intent) {

    wifiSRList = wifiManager.getScanResults();

    if (wifiSRList.size() == 0) {
        Toast.makeText(context,"wifi List 0",Toast.LENGTH_SHORT).show();
    }

    if (checkWifiSelected) {
        LayoutInflater wifiLayout = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View wifiView = wifiLayout.inflate(R.layout.dialog_fragment_wifi,null);

        AlertDialog.Builder wifiDialog = new AlertDialog.Builder(context);
        wifiDialog.setCancelable(false);
        wifiDialog.setView(wifiView);

        wifiAlertDialog = wifiDialog.create();
        wifiListView = (ListView)wifiView.findViewById(R.id.user_wifi_detail);
    }


    Collections.sort(wifiSRList, new Comparator<ScanResult>() {
        @Override
        public int compare(ScanResult lhs, ScanResult rhs) {
            return (lhs.level > rhs.level ? -1 : (lhs.level == rhs.level ? 0 : 1));
        }
    });


    if (checkWifiSelected) {
        String[] wifiListString = new String[wifiSRList.size()];

        for (int i = 0; i < wifiSRList.size(); i++) {
            wifiListString[i] = (wifiSRList.get(i).SSID);
        }

        wifiListView.setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, wifiListString));

        wifiAlertDialog.show();
        progress.dismiss();

        wifiListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                operator = wifiSRList.get(position).SSID;
                macAddress = wifiSRList.get(position).BSSID;
                signalStrength = wifiSRList.get(position).level;
                frequency = wifiSRList.get(position).frequency;

                final String cap = wifiSRList.get(position).capabilities;
                final String[] securityModes = {WEP, WPA2, EAP};
                for (int i = securityModes.length - 1; i >= 0; i--) {
                    if (cap.contains(securityModes[i])) {
                        security = securityModes[i];
                    }
                }

                setOperator(operator);
                GetSetClass.wifiOperator = operator;

                /* error start ..cannot resolved method getPreferences() */
                SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE); // error line
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString(STORED_OPERATOR, operator);
                editor.apply();
                /* error end */

                operatorName = operator;
                setMacAddress(macAddress);
                setSignalStrength(signalStrength);
                setFrequency(frequency);
                setSecurity(security);
                setChannelNumber(convertFrequencyToChannel(frequency));
                wifiAlertDialog.dismiss();

                checkWifiSelected = false;
            }
        });
    }

    if(checkServayStart) {
        /* error start ..cannot resolved method getPreferences()*/
        SharedPreferences shPref = context.getPreferences(Context.MODE_PRIVATE); // error line
        String savedOperator = shPref.getString(STORED_OPERATOR,null);

        Log.e("operator : ", "saved operator is : " + savedOperator);
        /* error end */

        if (wifiSRList != null) {
            ssidCount = wifiSRList.size();
            for(int i = wifiSRList.size() - 1; i >= 0; i--) {
                if (GetSetClass.wifiOperator.equals(wifiSRList.get(i).SSID)) {
                    String requiredOperator = wifiSRList.get(i).SSID;
                        requiredLevel = wifiSRList.get(i).level;
                        context.unregisterReceiver(this);
                    AlertDialog.Builder myBuilder = new AlertDialog.Builder(context);

                    setRequiredLevel(requiredLevel);

                    myBuilder.setTitle("Current Signal");
                    myBuilder.setMessage("Operator : " + requiredOperator + " \n\nSignal Strength : " + requiredLevel + " dBm");
                    myBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    myBuilder.show();
                } else {
                    Toast.makeText(context,"Operator Mismatch",Toast.LENGTH_SHORT).show();
                }
            }

            progress.dismiss();
        }
    }
}

public static int convertFrequencyToChannel(int freq) {
    if (freq >= 2412 && freq <= 2484) {
        return (freq - 2412) / 5 + 1;
    } else if (freq >= 5170 && freq <= 5825) {
        return (freq - 5170) / 5 + 34;
    } else {
        return -1;
    }
}
}

更新的答案:

private static final String STORED_FILE = "com.package.name.SELECTED_FILE";
private static final String STORED_OPERATOR = "com.package.name.SELECTED_OPERATOR";

将数据保存到 SharedPreferences :

SharedPreferences sharedPref = context.getSharedPreferences(STORED_FILE,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(STORED_OPERATOR, operator);
editor.apply();

从 SharedPreferences 获取数据:

SharedPreferences shPref = context.getSharedPreferences(STORED_FILE,Context.MODE_PRIVATE);
String savedOperator = shPref.getString(STORED_OPERATOR,null);

Log.e("operator : ", "saved operator is : " + savedOperator);

最佳答案

如果我没理解错的话,您需要的是一种机制来保存用户之前选择的 WiFi 网络(如果有的话)。

您可以使用 SharedPreferences 实现此目的.

onReceive 方法的开头,您查询应用的共享首选项以查找任何已保存的 WiFi SSID:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String savedSsid = sharedPref.getString("saved_wifi_ssid", null);

如果 savedSsid 不为空,则用户之前选择了 WiFi,您可以跳过显示对话框:

if (savedSsid != null) {
    // Do whatever you need to do with the stored SSID.
    // Return from onReceive to avoid displaying your dialog.
    return;
}

您需要做的最后一件事是将选定的 WiFi SSID 存储为 onItemClick 的一部分:

wifi_SSID = wifiList.get(position).SSID;
// ... other code ...
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("saved_wifi_ssid", wifi_SSID);
editor.commit();

参见 the Android Developer Guide有关 SharedPreferences 的更多信息。


更新

对于您的特定用例,即 BroadcastReceiver 作为独立类驻留,您需要通过 Context 实例访问 SharedPreferences,您在 onReceive 中作为参数接收 像这样:

SharedPreferences sharedPref = context.getSharedPreferences("name_for_your_shared_preferences_file", Context.MODE_PRIVATE);

此行应替换该行的两次出现:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

参见 documentation对于 getSharedPreferences(String, int)。

关于java - 如何在 Android 中一次又一次地从 wifi 列表中选择相同的 wifi 运营商?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31992164/

有关java - 如何在 Android 中一次又一次地从 wifi 列表中选择相同的 wifi 运营商?的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  3. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  4. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  5. ruby - 如何每月在 Heroku 运行一次 Scheduler 插件? - 2

    在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/

  6. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  7. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  8. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  9. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

  10. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

随机推荐