如何将 Android Wifi 扫描结果添加到列表中?

Posted

技术标签:

【中文标题】如何将 Android Wifi 扫描结果添加到列表中?【英文标题】:How can I get Android Wifi Scan Results into a list? 【发布时间】:2011-07-24 02:26:42 【问题描述】:

我知道如何获得<List>android Wifi 扫描,但我想不出用它们制作列表适配器的最佳方法。我只想将扫描的<List> 中的 SSID 和 BSSID 绑定到 text1 和 text2。

我一直在做的示例

wifi.startScan();
        // get list of the results in object format ( like an array )
        List<ScanResult> results = wifi.getScanResults();`

        // loop that goes through list
        for (ScanResult result : results) 
            Toast.makeText(this, result.SSID + " " + result.level,
                    Toast.LENGTH_SHORT).show();

还有:

private void fillDataFromDb() 
        Cursor scanCursor = Db.fetchAllScans();
        startManagingCursor(scanCursor);`

        // Create an array to specify the fields we want to display in the list
        // (only TITLE)
        String[] from = new String[]  WifiDbAdapter.KEY_BSSID,
                WifiDbAdapter.KEY_SSID ;

        // and an array of the fields we want to bind those fields to (in this
        // case just text1)
        int[] to = new int[]  R.id.text1, R.id.text2 ;

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter scansdb = new SimpleCursorAdapter(this,
                R.layout.scan_row, scanCursor, from, to);
        setListAdapter(scansdb);
    

【问题讨论】:

我想看看你也有一些代码。你得到这样的结果了吗?: List results = wifi.getScanResults(); 我已经这样做了,只是为了获取 toast 消息:wifi.startScan(); // get list of the results in object format ( like an array ) List&lt;ScanResult&gt; results = wifi.getScanResults(); // loop that goes through list for (ScanResult result : results) Toast.makeText(this, result.SSID + " " + result.level, Toast.LENGTH_SHORT).show(); @eternalmatt 是的,这正是我获得结果的方式,而且效果很好,只是不知道如何将其绑定到列表视图 【参考方案1】:

试试这个代码

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) getApplicationContext().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)
                  
        

WiFiDemo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:layout_margin="16dp"
    android:orientation="vertical">

    <LinearLayout
        android:layout_
        android:layout_
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textStatus"
            android:layout_
            android:layout_
            android:layout_weight="1"
            android:text="Status" />

        <Button
            android:id="@+id/buttonScan"
            android:layout_
            android:layout_
            android:text="Scan" />
    </LinearLayout>

    <ListView
        android:id="@+id/list"
        android:layout_
        android:layout_
        android:layout_marginTop="20dp"></ListView>
</LinearLayout>

对于 ListView-row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="vertical"
    android:padding="8dp">

    <TextView
        android:id="@+id/list_value"
        android:layout_
        android:layout_
        android:textSize="14dp" />
</LinearLayout>

AndroidManifest.xml

中添加这些权限
<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_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

【讨论】:

非常感谢这段代码。在wifi listview上敲了这么多天后,我终于去工作了 谢谢,没想到这么简单。 :) 取消注册广播接收器怎么样? textStatus 没用。 感谢您提供此代码。如何在列表中连续扫描 Wifi 并返回 RSS 值?【参考方案2】:

除了接受的答案之外,您还需要在 AndroidManifest 中获得以下权限才能使其正常工作:

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 

【讨论】:

【参考方案3】:

ArrayAdapter 包裹在您的List&lt;ScanResult&gt; 周围。覆盖 getView() 以使用 ScanResult 数据填充您的行。 Here is a free excerpt 来自我的一本书,其中介绍了如何像这样创建自定义 ArrayAdapters

【讨论】:

你能给我这个问题的演示吗 这本书看起来不错。谢谢【参考方案4】:

在下面找到一个完整的工作示例:

@Android 的代码非常好,但问题很少,即:

    填充到 ListView 代码需要移动到 BroadCastReceiver 的 onReceive,其中只有结果可用。如果在第二次尝试时获得结果。 BroadCastReceiver在获取结果后需要注销。 size = size -1 似乎没有必要。

在下面找到@Android的修改代码作为一个工作示例:

WifiScanner.java 这是主要活动

package com.arjunandroid.wifiscanner;

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.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

public class WifiScanner extends Activity implements View.OnClickListener


    WifiManager wifi;
    ListView lv;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;

    String ITEM_KEY = "key";
    ArrayList<String> arraylist = new ArrayList<>();
    ArrayAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    
        super.onCreate(savedInstanceState);
        getActionBar().setTitle("Widhwan Setup Wizard");

        setContentView(R.layout.activity_wifi_scanner);

        buttonScan = (Button) findViewById(R.id.scan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.wifilist);


        wifi = (WifiManager) getApplicationContext().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 ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arraylist);
        lv.setAdapter(this.adapter);

        scanWifiNetworks();
    

    public void onClick(View view)
    
        scanWifiNetworks();
    

    private void scanWifiNetworks()

        arraylist.clear();
        registerReceiver(wifi_receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

        wifi.startScan();

        Log.d("WifScanner", "scanWifiNetworks");

        Toast.makeText(this, "Scanning....", Toast.LENGTH_SHORT).show();

    

    BroadcastReceiver wifi_receiver= new BroadcastReceiver()
    

        @Override
        public void onReceive(Context c, Intent intent)
        
            Log.d("WifScanner", "onReceive");
            results = wifi.getScanResults();
            size = results.size();
            unregisterReceiver(this);

            try
            
                while (size >= 0)
                
                    size--;
                    arraylist.add(results.get(size).SSID);
                    adapter.notifyDataSetChanged();
                
            
            catch (Exception e)
            
                Log.w("WifScanner", "Exception: "+e);

            


        
    ;


activity_wifi_scanner.xml 是 Activity 的布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dp"
    android:layout_
    android:layout_>

    <ListView
        android:id="@+id/wifilist"
        android:layout_
        android:layout_
        android:layout_weight="0.97" />


    <Button
        android:id="@+id/scan"
        android:layout_
        android:layout_
        android:layout_gravity="bottom"
        android:layout_margin="15dp"
        android:background="@android:color/holo_green_light"
        android:text="Scan Again" />
</LinearLayout>

同上,别忘了在AndroidManifest.xml中添加Wifi权限

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 

【讨论】:

【参考方案5】:

请参阅下面的链接以获取从列表中删除冗余 ssid 的 ScanResult

duplicate SSID in scanning wifi result

【讨论】:

以上是关于如何将 Android Wifi 扫描结果添加到列表中?的主要内容,如果未能解决你的问题,请参考以下文章

Android 11.0 修复Settings→wifi→添加网络→扫描二维码界面上下压缩

《Android源码设计模式》--状态模式

在oracle中将行值添加到列

如何将mysql内部连接结果从行分组到列

在 Android 应用程序中控制 wifi 文档扫描仪

将多个值添加到列中 - Pandas