Access Android hardware resources and manage network and Wi-Fi connections

Source: Internet
Author: User
Tags bssid

(1) connectivitymanager

In Android, The connectivitymanager class represents the network connection service, which is used to monitor the network connection status, configure invalid reconnection, and control the network antenna. To obtain a connectivity manager instance, use getsystemservice and specify context. connectivity_service as the parameter. The code snippet is as follows:

String cservicename = context. connectivity_service; <br/> connectivitymanager CM = (connectivitymanager) getsystemservice (cservicename); <br/>To use connectivity manager to read and write network statuses, you must add the following license to the androidmanifest. xml file:<Uses-Permission Android: Name = "android. permission. access_network_state "/> <br/> <uses-Permission Android: Name =" android. permission. change_network_state "/> <br/>

Connectivity manager provides interfaces for managing available network connections at a higher level. The getactivenetworkinfo and getnetworkinfo functions can be used to query and obtain networkinfo objects, this object contains the details of the current active network connection or the specified type of unavailable network connection.

1.1) set the preferred network

When any authenticated application requests a network connection, Android will give priority to the preferred network connection. The setnetworkpreference function is used to set the preferred network connection. The code snippet is as follows:

Cm. setnetworkpreference (connectivitymanager. type_wifi); <br/>

When the preferred network connection is unavailable or the connection is lost, Android automatically attempts to use the second preferred connection type.


1.2) Monitoring Network Connection

One of the most common functions of connectivitymanager is to notify the application when the network connection status changes. This is achieved through the application's own broadcast receiver to listen to intvitymanager. connectivity_action intent. This intent provides the following types of extra to further clarify the network status that has changed:

1) connectivitymanager. extra_is_failover: The value true indicates that the current connection is the first connection after the network is reconnected;

2) connectivitymanager. extra_no_connectivity: The value true indicates that the current device is not connected to the network;

3) connectivitymanager. extra_reason: if the current broadcast indicates that the network is invalid, this value contains the reason for the connection failure;

4) connectivitymanager. extra_network_info: returns the networkinfo object, which contains network details related to the current connection event;

5) connectivitymanager. extra_other_network_info: When a network is disconnected, this value returns the networkinfo object, which contains detailed information about possible network reconnection failures;

6) connectivitymanager. extra_extra_info: contains additional information about optional network connections.


(2) wifimanager

Wifimanager stands for the Wi-Fi connection service in Android. It is used to configure Wi-Fi network connections and manage the current Wi-Fi connection, scans Wi-Fi access points and monitors changes in the status of Wi-Fi connections. The method for obtaining wifimanager is similar to that of connectivity Manager. The getsystemservice function provides the context. wifi_service parameter. The code snippet is as follows:

String wservicename = context. wifi_service; <br/> wifimanager WM = (wifimanager) getsystemservice (wservicename); <br/>

Similarly, you must specify the access permission in the androidmanifest. xml file:

<Uses-Permission Android: Name = "android. permission. access_wifi_state "/> <br/> <uses-Permission Android: Name =" android. permission. change_wifi_state "/> <br/>

You can use the setwifienabled function to set the Enable and disable Wi-Fi hardware, and use the getwifistate and iswifienabled functions to view the current Wi-Fi status. The code snippet is as follows:

If (! WM. iswifienabled () {<br/> If (wifimanager. wifi_state_enabling! = WM. getwifistate () {<br/> WM. setwifienabled (true); <br/>}< br/>}


 

2.1) monitor Wi-Fi connections

When the Wi-Fi network connection status changes, the Wi-Fi manager broadcasts the corresponding intent, which includes the following types:

1) wifimanager. wifi_state_changed_action: identifies a change in the Wi-Fi hardware status, which may change between enabling, enabled, disabling, disabled, and unknown. It contains two additional key values: extra_wifi_state and extra_previus_state, indicating the new and previous Wi-Fi statuses respectively.

2) wifimanager. supplicant_connection_change_action: when the connection status between the Wi-Fi hardware and the current access point changes, this intent will be broadcast. The additional key value extra_new_state is used to indicate whether a new connection establishment event or an existing connection interruption event. True indicates that a new connection is established.

3) wifimanager. network_state_changed_action: This intent is broadcast when the Wi-Fi connection status changes. It contains two additional key values: extra_network_info, which contains the networkinfo object indicating the current network status, and extra_bssid, contains the bssid value of the connected access point.

4) wifimanager. rssi_changed_action: Listening to this intent allows the application to monitor the signal strength of the current Wi-Fi connection. Contains an additional key value extra_new_arg, which contains the current signal strength. To use this signal strength, you need to use the static function calculatesignallevel to convert this value to an integer value according to the specified scaling.


2.2) create and manage Wi-Fi connections and configurations

You can use WiFi manager to configure the network to control which network to connect. After the connection is established, You can further obtain additional configuration information for the active network connection. Use the getconfigurednetworks function to obtain the list of current network configuration information. The returned value is the wificonfiguration object, which contains the network ID, SSID, and other configuration information.

To use a network connection, you can use the enablenetwork function to pass in the network ID and set the disableallothers parameter to true. The code snippet is as follows:

// Get a list of available deployments <br/> List <wificonfiguration> deployments = WM. getconfigurednetworks (); <br/> // get the network ID for the first one <br/> If (deployments. size ()> 0) {<br/> int netid = tolerations. get (0 ). networkid; <br/> // enable the network <br/> Boolean disableallothers = true; <br/> WM. enablenetwork (netid, disableallothers); <br/>}

Once the connection is established, you can use the getconnectioninfo function to return the connection status. The returned result is a wifiinfo object that contains the bssid, MAC address, IP address, and current link speed and signal strength of the Access Point.

The following code snippet is used to query the currently active wi-fi connection and display the obtained information:

Wifiinfo info = WM. getconnectioninfo (); <br/> If (null! = Info. getbssid () {<br/> int strength = wifimanager. calculatesignallevel (info. getarg (), 5); <br/> int speed = info. getlinkspeed (); <br/> string Units = wifiinfo. link_speed_units; <br/> string SSID = info. getssid (); </P> <p> string toasttext = string. format ("connected to {0} At {1} {2 }. strength {3}/5 ", SSID, speed, units, strength); <br/> toast. maketext (this. getapplicationcontext (), toasttext, toast. length_long); <br/>}

2.3) scan WiFi hotspots

You can use the startscan function to scan the Wi-Fi access point. When the scan is complete and the result is available, wifimanager will send an intent of the scan_results_available_actionl type. You can use the getscanresults function to obtain the scan result information and save it to the scanresult object. The scanresult object contains detailed information about each detected access point, including link speed, signal strength, SSID, and supported authentication technologies. The following code snippet shows the WiFi hotspot scanning process:

// Register a broadcast receiver er that listens for scan results <br/> registerreceiver (New broadcastreceiver () {</P> <p> @ override <br/> Public void onreceive (context, intent) {<br/> List <scanresult> Results = wifi. getscanresults (); <br/> scanresult bestsignal = NULL; <br/> for (scanresult result: Results) {<br/> If (null = bestsignal | <br/> wifimanager. comparesignallevel (bestsignal. level, result. level) <0) {<br/> bestsignal = result; <br/>}</P> <p> string toasttext = string. format ("{0} networks found. {1} is the strongest. ", <br/> results. size (), bestsignal. SSID); <br/> toast. maketext (getapplicationcontext (), toasttext, toast. length_long); <br/>}</P> <p >}, new intentfilter (wifimanager. scan_results_available_action); </P> <p> // initiate a scan <br/> wifi. startscan ();

To connect to the network, you need to create and register a Wi-Fi configuration. Generally, you can use the android native wifi configuration program, but we can also provide the same function in our own applications, setting completely replaces the native wifi configuration program, which requires the wificonfiguration class that saves the network configuration information. Each wifi configuration generally contains the following public data items:

1) bssid: Specifies the bssid of the Access Point;

2) SSID: The SSID of a specific network;

3) networkid: the network configuration ID that uniquely identifies the current device;

4) Priority: select the priority of each network configuration to be used to connect to the access point;

5) status: the status of the current network connection. The values are as follows:

Wificonfiguration. Status. enabled, wificonfiguration. Status. Disabled,

Wificonfiguration. Status. Current.

The wificonfiguration object also includes the supported authentication technologies and keys used for authentication with access points.

The addnetwork function can be used to add new WiFi configurations to the current WiFi list. Similarly, the updatenetwork function can be used to update some information about an existing wifi configuration; the removenetwork function is used to remove configuration information. To save any changes to the network configuration, call the saveconfiguration function.

Related Article

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.