Je sais comment obtenir un des scans Wifi Android, mais je ne peux pas trouver le meilleur moyen de créer un adaptateur de liste à partir d’eux. Je voudrais juste lier SSID et BSSID d'un des balayages à text1 et text2.
Des exemples de ce que j'ai fait
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();
Et:
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);
}
Essayez ce code
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_width="match_parent"
Android:layout_height="match_parent"
Android:layout_margin="16dp"
Android:orientation="vertical">
<LinearLayout
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:gravity="center_vertical"
Android:orientation="horizontal">
<TextView
Android:id="@+id/textStatus"
Android:layout_width="0dp"
Android:layout_height="wrap_content"
Android:layout_weight="1"
Android:text="Status" />
<Button
Android:id="@+id/buttonScan"
Android:layout_width="wrap_content"
Android:layout_height="40dp"
Android:text="Scan" />
</LinearLayout>
<ListView
Android:id="@+id/list"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:layout_marginTop="20dp"></ListView>
</LinearLayout>
Pour ListView- row.xml
<?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="wrap_content"
Android:orientation="vertical"
Android:padding="8dp">
<TextView
Android:id="@+id/list_value"
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:textSize="14dp" />
</LinearLayout>
Ajoutez ces autorisations dans 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" />
En plus de la réponse acceptée, vous aurez besoin des autorisations suivantes dans votre AndroidManifest pour le faire fonctionner:
<uses-permission Android:name="Android.permission.ACCESS_WIFI_STATE" />
<uses-permission Android:name="Android.permission.CHANGE_WIFI_STATE" />
Enroulez une ArrayAdapter
autour de votre List<ScanResult>
. Remplacez getView()
pour renseigner vos lignes avec les données ScanResult
. Voici un extrait gratuit de l'un de mes livres qui explique comment créer une ArrayAdapters
personnalisée comme celle-ci.
Trouvez un exemple de travail complet ci-dessous:
Le code de @Android est très bon mais a quelques problèmes, à savoir:
size = size -1
semble inutile.Trouvez ci-dessous le code modifié de @Android comme exemple de travail:
WifiScanner.Java qui est l'activité principale
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, qui est le fichier de mise en forme de l'activité
<?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_width="match_parent"
Android:layout_height="match_parent">
<ListView
Android:id="@+id/wifilist"
Android:layout_width="match_parent"
Android:layout_height="312dp"
Android:layout_weight="0.97" />
<Button
Android:id="@+id/scan"
Android:layout_width="match_parent"
Android:layout_height="50dp"
Android:layout_gravity="bottom"
Android:layout_margin="15dp"
Android:background="@Android:color/holo_green_light"
Android:text="Scan Again" />
</LinearLayout>
Également, comme mentionné ci-dessus, n'oubliez pas d'ajouter des autorisations Wifi dans le fichier AndroidManifest.xml.
<uses-permission Android:name="Android.permission.ACCESS_WIFI_STATE" />
<uses-permission Android:name="Android.permission.CHANGE_WIFI_STATE" />
référez-vous au lien ci-dessous pour obtenir ScanResult avec le ssid redondant supprimé de la liste