Android Development-Get WiFi list

Source: Internet
Author: User
Tags get ip bssid

Recently, bloggers are learning frangment framework, so they want to think about it through the listfragment to get the WiFi list.

Good!

Don't talk nonsense now.

I. Basic knowledge of WIFI

The following five statuses are defined in the official Android documentation:

Wifi_state_disabling? WiFi card is shutting down? 0

wifi_state_disabled? WiFi nic not available? 1
wifi_state_enabling?? WiFi card is open? 2
wifi_state_enabled?? WiFi nic available? 3
Wifi_state_unknown?? WiFi card status not known 4


To get WiFi information, you need a Wifimanager object, and

Wifimanager Object You need to use Context. Getsystemservice (Context.wifi_service) to get the Wifimanager object.

Here we need to know that things like activity inherit from Context , so that . getsystemservice (Context.wifi_service) to

Gets the object. Suppose you want to get a list of WiFi hotspots around you, you can use Wifimanager.getscanresults () to return a list of Scanresult

The following is the basic knowledge of the relevant WiFi reproduced from other bloggers

(1) Scanresult

Mainly through the WiFi hardware scan to get some of the surrounding WiFi hotspot information. When we do a WiFi search, this information is usually found, first, the access point name, the strength of the access point information, and the security mode used by the access point. is WPA, WPE; Open this class, we can see the following information BSSID access point address, here mainly refers to a small range of wireless devices connected to the address obtained. Let's say two laptops are connected through a wireless card, and the two-party wireless card assigns the address.
The name of the SSID network. When we search for a network, this is what distinguishes each of the different network access points.
Capabilities Network access performance, here is mainly to infer the network encryption method and so on.
Frequency frequency, the number of MHz that each channel interacts with.


Level. Primarily to infer the priority number of network connections.
Here's just one way to do this. is to get the information programming string ToString ().

(2) Wificonfiguration

When we connect to a WiFi access point. Some information that needs to be obtained.

You can compare it with our wired equipment.
The data here is relatively complex.
Six sub-classes
Wificonfiguration.authalgorthm is used to infer encryption methods.


Wificonfiguration.groupcipher Gets the method that uses Groupcipher to encrypt.
Wificonfiguration.keymgmt get used with KEYMGMT.
Wificonfiguration.pairwisecipher gets the encryption using WPA mode.
Wificonfiguration.protocol gets which protocol is used for encryption.


Wificonfiguration.status gets the status of the current network.
For those who are interested in encryption, you can search for relevant content on the Internet.


To set the properties of a wificonfiguration:
Wificonfiguration.authalgorthm set the encryption method.
Optional parameters: Leap is only used for leap,
OPEN is WPA/WPA2 required,
GKFX requires a static WEP key
Wificonfiguration.groupcipher uses the Groupcipher method to encrypt.
Optional references: CCMP,TKIP,WEP104,WEP40
WIFICONFIGURATION.KEYMGMT Key Management mechanism (keymanagerment). Use the KEYMGMT.
Optional number of references Ieee8021x,none,wpa_eap,wpa_psk
Wificonfiguration.pairwisecipher set the encryption method.
Optional number of references Ccmp,none,tkip
Wificonfiguration.protocol sets a protocol for encryption.


Optional number of RSN,WPA,
Wificonfiguration.status sets the status of the current network.
Optional number of references current,disabled,enabled

(3) Wifiinfo

After our WiFi has been connected. The ability to get some information about a connected WiFi connection through this class gets the information of the current link,
The information here is simpler. Here is a brief introduction to the method here:
Getbssid () Get Bssid
Getdetailedstateof () Get the connectivity of the client
Gethiddenssid () gets whether the SSID is hidden
Getipaddress () Get IP address
Getlinkspeed () Get the speed of the connection
Getmacaddress () Get MAC Address
Getrssi () Get signal from 802.11n network
Getssid () Get SSID
Getsupplicanstate () returns information about the client state in detail

(4) Wifimanager

This needless to say, is used to manage our WiFi connection. Some classes have been defined here that can be used by us.
It's relatively complex here, and it's a lot more, but by literal means we can still get a lot of relevant information. Many constants are predefined in this class. We are able to use it directly without having to create it again.
Here's a brief introduction to the method here:
Addnetwork (wificonfiguration config) joins the network by acquiring the link state information of the network
Calculatesignallevel (int rssi, int numlevels) calculates the rank of the signal
Comparesignallevel (int rssia, int rssib) against connection A and connection B
Createwifilock (int lockType, String tag) creates a WiFi lock that locks the current WiFi connection
disablenetwork (int netId) to invalidate a network connection
Disconnect () disconnect
Enablenetwork (int netId, Boolean disableothers) connects a connection
Getconfigurednetworks () Get the status of a network connection
Getconnectioninfo () Get information about the current connection
Getdhcpinfo () Getting DHCP information
Getscanresulats () Gets the results of the scan test
Getwifistate () Get a WiFi access point is valid
Iswifienabled () infer if a WiFi connection is valid
Pingsupplicant () ping a connection. Infer whether connectivity is possible
Ressociate () Even if the connection is not ready, it must be connected
Reconnect () Suppose the connection is ready, connected
Removenetwork () Removing a network
Saveconfiguration () Keep a configuration message
Setwifienabled () make a connection valid
Startscan () Start scanning
Updatenetwork (wificonfiguration config) update information for a network connection
In addition, Wifimanaer also provides an internal subclass, that is, the role of Wifimanagerlock,wifimanagerlock is this,
In a normal state, let's say that our WiFi status is idle. Then the network connectivity, will be temporarily interrupted.


However, if we lock the current network status, then WiFi connectivity will remain in a certain state. Of course after the contact is locked. It will return to normal.

All right. Don't say much nonsense, I'll stick to the code map below.


Mainfest's Code Map

<?xml version= "1.0" encoding= "Utf-8"?

><manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "Com.example.wifilisttest" Android:versioncode= "1" android:versionname= "1.0" > <!--The following are the permissions required to access the network using WiFi--<uses-permission Android:name= "Android.permission.CHANGE_NETWORK_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_WIFI_STATE "/> <uses-sdk A ndroid:minsdkversion= "android:targetsdkversion="/> <application android:allowbackup= "true" android:icon= "@drawable/kkk99" android:label= "@string/app_name" android:theme= "@style/apptheme" > <activity android:name= ". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "ANdroid.intent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> </intent-filter> </activity> </application></manifest>

Mainactivity

Package Com.example.wifilisttest;import Java.util.list;import Android.app.activity;import android.content.Context; Import Android.net.wifi.scanresult;import Android.net.wifi.wifimanager;import Android.os.bundle;import Android.support.v4.app.fragmentactivity;import Android.support.v4.app.fragmentmanager;import Android.view.Menu; Import Android.view.menuitem;import Android.widget.button;import Android.widget.toast;public class MainActivity    Extends Fragmentactivity {private Wifimanager wifimanager;    List<scanresult> list;    String[] Flist=null; Button but; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);          Fragment1 f1 = new Fragment1 ();          Fragmentmanager manager = Getsupportfragmentmanager ();         Manager.begintransaction (). Add (r.id.fragments, F1). commit (); } @Overridepublic Boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it isPresent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} @Overridepublic boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. The action bar will//automatically handle clicks on the Home/up button so long//as you specify a parent activity in and RoidManifest.xml.int id = item.getitemid (); if (id = = r.id.action_settings) {return true;} return super.onoptionsitemselected (item);}}

Fragment1

Package Com.example.wifilisttest;import java.util.ArrayList;  Import Java.util.HashMap;  Import java.util.List;    Import Java.util.Map;  Import android.app.Activity; Import Android.content.context;import Android.net.wifi.scanresult;import Android.net.wifi.wifimanager;import  Android.os.Bundle;  Import android.support.v4.app.ListFragment;  Import Android.util.Log;  Import Android.view.LayoutInflater;  Import Android.view.View;  Import Android.view.ViewGroup;  Import Android.widget.ListView;  Import Android.widget.SimpleAdapter;  Import Android.widget.TextView;    Import Android.widget.Toast; /** * @ Descriptive narrative to use the ListView in fragment. Use listfragment * * */public class Fragment1 extends Listfragment {private String TAG = Fragment1.class.getName      ();      Private ListView list;      Private Simpleadapter adapter;    List<scanresult> Llll=null;    String[] flist;private TextView tv;private Wifimanager Wifimanager; list<scanresult> listb;/** * @ descriptive narrative in Oncreateviewinto layout * */@Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bund          Le Savedinstancestate) {View view = Inflater.inflate (R.layout.fragment1, Container,false); List = (ListView) View.findviewbyid (Android.          R.id.list);        tv= (TextView) View.findviewbyid (r.id.tv);                Tv.settext ("Nulltitle");          LOG.I (TAG, "--------Oncreateview");      return view;                 } @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);          Bundle B = savedinstancestate;          LOG.I (TAG, "--------onCreate");        Wifimanager = (Wifimanager) getactivity (). Getsystemservice (Context.wifi_service);        Listb = Wifimanager.getscanresults ();        Array initialization to note string[] listk=new string[listb.size ()];            if (Listb!=null) {for (int i=0;i<listb.size (); i++) {Scanresult Scanresult = Listb.get (i); Listk[i]=scanreSult.            SSID;        }} string[] List0=new string[listb.size ()];        if (listb==null) {list0[0]= "Nowifi";}        else{List0=listk; }//Set Fragment1 corresponding R.layout.listtest this layout file adapter = new Simpleadapter (getactivity (), GetData (list0), r.layout          . listtest, new string[]{"title"}, New Int[]{r.id.title});                Setlistadapter (adapter); } @Override public void Onlistitemclick (ListView l, View v, int position, long id) {Super.onlist          ItemClick (l, V, position, id);        Scanresult Scanresult = listb.get (position); if (wifimanager.setwifienabled (True)) {Toast.maketext (Getactivity (), Scanresult.ssid+position, Toast.LENGTH        _long). Show ();        } else{Toast.maketext (Getactivity (), "WiFi Not Open", Toast.length_long). Show ();          } System.out.println (L.getchildat (position)); Hashmap<string, object> view= (hashmap<string, object>) L.getitemAtposition (position);                                  System.out.println (View.get ("title"). ToString () + "+++++++++title");          Toast.maketext (Getactivity (), tag+l.getitemidatposition (position), Toast.length_long). Show ();                    System.out.println (v);                          System.out.println (position); } private list<?

Extends Map<string,?

>> getData (string[] strs) {list<map<string,object>> List = new Arraylist<map<string,obj Ect>> (); for (int i = 0; i < strs.length; i++) {map<string, object> Map = new hashmap<string, object> ( ); Map.put ("title", Strs[i]); List.add (map); } return list; } @Override public void onactivitycreated (Bundle savedinstancestate) {super.onactivitycreated (Savedi Nstancestate); LOG.I (TAG, "--------onactivitycreated"); } @Override public void Onattach (activity activity) {Super.onattach (activity); LOG.I (TAG, "----------Onattach"); } }


Activity_main.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    xmlns:tools=" Http://schemas.android.com/tools "    android:layout_width=" Match_parent    " android:layout_height= "Match_parent"    tools:context= ". Mainactivity ">    <framelayout         android:id=" @+id/fragments "        android:layout_width=" Wrap_content "        android:layout_height= "Wrap_content"        ></FrameLayout></LinearLayout>
Fragment1.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:o rientation= "vertical" >      <textview           android:id= "@+id/tv"        android:layout_width= "Fill_parent"          android:layout_height= "wrap_content"          android:gravity= "center"                   />            <listview           Android:id= "@id/android:list"          android:layout_width= "fill_parent"          android:layout_height= "wrap_content "          ></ListView>    


Listtest.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:orientation=" vertical "> <textview Android:id= "@+id/title" android:layout_width= "wrap_content" android:layout_height= "wrap_content" / > </LinearLayout>


Code download

Android Development-Get WiFi list

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.