Android net wifi wifimanager

Содержание
  1. Wi-Fi и много других аббревиатур. Как в Android приложении получить данные об узлах Wi-Fi и не опухнуть
  2. 1. Создаем проект
  3. 2. Разрешения на доступы
  4. 3. Создаем BroadcastReceiver и подписываемся на события обновления данных о сканировании сетевого окружения Wi-Fi
  5. 4. Смотрим на ScanResult и разбираемся в терминах
  6. 5. Разбираемся в аббревиатурах и парсим capabilities
  7. 6. Создаем модель и функцию парсинга
  8. 8. Смотрим результат
  9. WifiManager
  10. Class Overview
  11. Summary
  12. Constants
  13. public static final String ACTION_PICK_WIFI_NETWORK
  14. public static final String ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE
  15. public static final int ERROR_AUTHENTICATING
  16. public static final String EXTRA_BSSID
  17. public static final String EXTRA_NETWORK_INFO
  18. public static final String EXTRA_NEW_RSSI
  19. public static final String EXTRA_NEW_STATE
  20. public static final String EXTRA_PREVIOUS_WIFI_STATE
  21. public static final String EXTRA_RESULTS_UPDATED
  22. public static final String EXTRA_SUPPLICANT_CONNECTED
  23. public static final String EXTRA_SUPPLICANT_ERROR
  24. public static final String EXTRA_WIFI_INFO
  25. public static final String EXTRA_WIFI_STATE
  26. public static final String NETWORK_IDS_CHANGED_ACTION
  27. public static final String NETWORK_STATE_CHANGED_ACTION
  28. public static final String RSSI_CHANGED_ACTION
  29. public static final String SCAN_RESULTS_AVAILABLE_ACTION
  30. public static final String SUPPLICANT_CONNECTION_CHANGE_ACTION
  31. public static final String SUPPLICANT_STATE_CHANGED_ACTION
  32. public static final int WIFI_MODE_FULL
  33. public static final int WIFI_MODE_FULL_HIGH_PERF
  34. public static final int WIFI_MODE_SCAN_ONLY
  35. public static final String WIFI_STATE_CHANGED_ACTION
  36. public static final int WIFI_STATE_DISABLED
  37. public static final int WIFI_STATE_DISABLING
  38. public static final int WIFI_STATE_ENABLED
  39. public static final int WIFI_STATE_ENABLING
  40. public static final int WIFI_STATE_UNKNOWN
  41. public static final int WPS_AUTH_FAILURE
  42. public static final int WPS_OVERLAP_ERROR
  43. public static final int WPS_TIMED_OUT
  44. public static final int WPS_TKIP_ONLY_PROHIBITED
  45. public static final int WPS_WEP_PROHIBITED
  46. Public Methods
  47. public int addNetwork (WifiConfiguration config)
  48. public static int calculateSignalLevel (int rssi, int numLevels)
  49. public void cancelWps (WifiManager.WpsCallback listener)
  50. public static int compareSignalLevel (int rssiA, int rssiB)
  51. public WifiManager.MulticastLock createMulticastLock (String tag)
  52. public WifiManager.WifiLock createWifiLock (String tag)
  53. public WifiManager.WifiLock createWifiLock (int lockType, String tag)
  54. public boolean disableNetwork (int netId)
  55. public boolean disconnect ()
  56. public boolean enableNetwork (int netId, boolean disableOthers)
  57. public List getConfiguredNetworks ()
  58. public WifiInfo getConnectionInfo ()
  59. public DhcpInfo getDhcpInfo ()
  60. public List getScanResults ()
  61. public int getWifiState ()
  62. public boolean is5GHzBandSupported ()
  63. public boolean isDeviceToApRttSupported ()
  64. public boolean isEnhancedPowerReportingSupported ()
  65. public boolean isP2pSupported ()
  66. public boolean isPreferredNetworkOffloadSupported ()
  67. public boolean isScanAlwaysAvailable ()
  68. public boolean isTdlsSupported ()
  69. public boolean isWifiEnabled ()
  70. public boolean pingSupplicant ()
  71. public boolean reassociate ()
  72. public boolean reconnect ()
  73. public boolean removeNetwork (int netId)
  74. public boolean saveConfiguration ()
  75. public void setTdlsEnabled (InetAddress remoteIPAddress, boolean enable)
  76. public void setTdlsEnabledWithMacAddress (String remoteMacAddress, boolean enable)
  77. public boolean setWifiEnabled (boolean enabled)
  78. public boolean startScan ()
  79. public void startWps (WpsInfo config, WifiManager.WpsCallback listener)
  80. public int updateNetwork (WifiConfiguration config)
  81. Protected Methods
  82. protected void finalize ()

Wi-Fi и много других аббревиатур. Как в Android приложении получить данные об узлах Wi-Fi и не опухнуть

Однажды мне понадобилось сканировать из Android приложения сети Wi-Fi и получать подробную выкладку данных о точках доступа.

Тут пришлось столкнуться с несколькими трудностями: в офф.документации Android многие описанные классы стали deprecated (API level > 26), что никак не было в ней отражено; описание некоторых вещей в документации минимально (например поле capabilities класса ScanResult на момент написания не описано почти никак, хотя содержит много важных данных). Третья сложность может заключаться в том, что при первой близости с Wi-Fi, отличной от чтения теории и настройки роутера по localhost, приходится иметь дело с рядом аббревиатур, которые кажутся понятными по отдельности. Но может быть не очевидно, как их соотнести и структурировать (суждение субъективно и зависит от предыдущего опыта).

В данной статье рассмотрено как из Android кода получить исчерпывающие данные о Wi-Fi окружении без NDK, хаков, а лишь с помощью Android API и понять, как их интерпретировать.

Не будем тянуть и начнем писать код.

1. Создаем проект

Заметка рассчитана на тех, кто больше одного раза создавал Android проект, поэтому подробности данного пункта опускаем. Код ниже будет представлен на языке Kotlin, minSdkVersion=23.

2. Разрешения на доступы

Для работы с Wi-Fi из приложения понадобится получить от пользователя несколько разрешений. В соответствии с документацией, для того, чтобы осуществить сканирование сети на устройствах с ОС версий после 8.0, помимо доступа к просмотру состояния сетевого окружения нужен либо доступ на изменение состояния модуля Wi-Fi устройства, либо доступ к координатам (примерным или точным). Начиная с версии 9.0 необходимо запросить у пользователя и то и то, и при этом явно запросить у пользователя включить службу определения местоположения. Не забываем галантно объяснять пользователю, что это прихоть компании Google, а не наше желание устроить за ним слежку 🙂

Итого, в AndroidManifest.xml добавим:

А в коде, в котором есть ссылка на текущую Activity:

3. Создаем BroadcastReceiver и подписываемся на события обновления данных о сканировании сетевого окружения Wi-Fi

Метод WiFiManager.startScan в документации помечен как depricated с версии API 28, но офф. guide предлагает использовать его.

Итого, получили список объектов ScanResult.

4. Смотрим на ScanResult и разбираемся в терминах

Посмотрим на некоторые поля этого класса и опишем, что они означают:

SSID — Service Set Identifier – это название сети

BSSID – Basic Service Set Identifier – MAC адрес сетевого адаптера (Wi-Fi точки)

level — Received Signal Strength Indicator [dBm (русское дБм) — Децибел, опорная мощность 1 мВт.] — Показатель уровня принимаемого сигнала. Принимает значение от 0 до -100, чем дальше от 0, тем больше мощности сигнала потерялось по пути от Wi-Fi точки к вашему устройству. Подробнее можно посмотреть например на Википедии. Здесь же расскажу, что с помощью Android класса WifiManager можно проградуировать уровень сигнала по шкале от отличного до ужасного с выбранным вами шагом:

frequency — частота работы точки Wi-Fi [Гц]. Помимо самой частоты вас может заинтересовать так называемый канал. У каждой точки есть своя рабочая чистота. На момент написания текста наиболее популярным диапозоном Wi-Fi точек является 2.4 GHz. Но, если быть точнее, точка передает информацию на ваш телефон на пронумерованной частоте, близкой к названной. Количество каналов и значения соответствующих частот стандартизованы. Это сделано для того, чтобы точки поблизости работали на разных частотах, тем самым не создавая помехи друг другу и взаимно не понижая скорость и качество передачи. При этом точки работают не на одной частоте, а на диапазоне частот (пареметр channelWidth), называемом шириной канала. То есть точки, работающие на соседних (и не только на соседних, а даже на 3 от себя) каналах создают друг другу помехи. Вам может пригодится этот незамысловатый код, который позволяет вычислить номер канала по значению частоты для точек с частотой 2.4 и 5 Ghz:

capabilities — наиболее интересное поле для анализа, работа с которым потребовало много времени. Тут в строку записываются «возможности» точки. При этом подробности интерпритации строки в документации можно не искать. Вот несколько примеров того, что может лежать в этой строке:

5. Разбираемся в аббревиатурах и парсим capabilities

Стоит упомянуть, что классы пакета android.net.wifi.* использует под капотом linux-утилиту wpa_supplicant и результат вывода в поле capabilities является копией поля flags при сканировании.

Будем действовать последовательно. Рассмотрим сначала вывод такого формата, при котором внутри скобок элементы отделены знаком «-«:

Первое значение описывает т.н. метод аутентификации (authentication). То есть, какую последовательность действий должны произвести устройство и точка доступа, чтобы точка доступа позволила собой пользоваться и каким образом шифровать полезную нагрузку. На момент написания поста самые частые варианты это WPA и WPA2, при котором либо каждое подключаемое устройство напрямую, либо через т.н. RADIUS-сервер (WPA-Enterprice) предоставляет пароль по зашифрованному каналу. Скорее всего у вас дома точка доступа предоставляет подключение по этой схеме. Отличие второй версии от первой в болеее стойком шифре: AES против небезопасного TKIP. Также постепенно внедряется WPA3, более сложный и продвинутый. Теоритически может встретиться вариант с enterprice-решением CCKM (Cisco Centralized Key Managment), но мне так и не встретился.

Точка доступа могла быть настроена на аутентификацию по MAC-адресу. Или, если точка доступа предоставляет данные по устаревшему алгоритму WEP, то аутентификации фактически нет (секретный ключ тут и является ключом шифрования). Такие варианты отнесем к типу OTHER.
Ещё есть полюбившийся в общественных wi-fi метод со скрытым Captive Portal Detection — запрос аутентификации через браузер. Такие точки доступа выглядят для сканера как открытые (какими с точки зраения физического подключения и являются). Поэтому отнесем их к типу OPEN.

Второе значение можно обозначить как алгоритм использования ключей (key management). Является параметром метода аутентификации, о котором написано выше. Говорит о том, как именно происходит обмен ключами шифрования. Рассмотрим возможные варианты. EAP — используется в упомянутом WPA-Enterprice, использует базу данных для сверки введеных аутентификационных данных. SAE — используется в продвинутом WPA3, более устойчива к перебору. PSK — самый частый вариант, подразумевает ввод пароля и его передачу в зашифрованном виде. IEEE8021X — по международному стандарту (отличному от поддержанным семейством WPA). OWE (Opportunistic Wireless Encryption) является расширением стандарта IEEE 802.11, для точек, которые мы отнесли к типу OPEN. OWE обеспечивает безопасность данных, передаваемых по незащищенной сети, за счет их шифрования. Также возможен варинант когда ключей доступа нет, назовем такой вариант NONE.

Читайте также:  Star wars kotor 2 android mod

Третьим параметром является т.н. метод шифрования (encryption schemes) — как именно используется шифр для зашиты передаваемых данных. Перечислим варианты. WEP — использует поточный шифр RC4, секретный ключ является ключом шифрования, что в мире современной криптографии считается неприемлемым. TKIP — используется в WPA, CKIP — в WPA2. TKIP+CKIP — может быть указан в точках умеющих WPA и WPA2 для обратной совместимости.

Вместо трех элементов можно встретить одинокую пометку WEP:

Как мы обсудили выше, этого достаточно чтобы не конкретизировать алгоритм использования ключей, которого нет, и метода шифрования, которое одно по-умолчанию.

Теперь рассмотрим такую скобочку:

Это режим работы Wi-Fi или топология сетей Wi-Fi. Вам может встретиться Режим BSS (Basic Service Set) — когда есть одна точка доступа, через которую общаются подключенные устройства. Можно встретить в локальных сетях. Как правило точки доступа нужны для того, чтобы соединять устройства из разных локальных сетей, поэтому они являются частью Extended Service Sets — ESS. Тип IBSSs (Independent Basic Service Sets) говорит о том, что устройство является частью Peer-to-Peer сети.

Ещё может попасться флаг WPS:

WPS (Wi-Fi Protected Setup) — протокол полуавтоматической инициализации сети Wi-Fi. Для инициализации пользователь либо вводит 8-символьный пароль, либо зажимает кнопку на роутере. Если ваша точка доступа относится к первому типу и этот флажок высветился напротив имени вашей точки доступа, вам настоятельно рекомендуется зайти в админку и отключить доступ по WPS. Дело в том, что часто 8-значный PIN можно узнать по MAC-адресу, либо перебрать за обозримое время, чем кто-то нечистый на руку сможет воспользоваться.

6. Создаем модель и функцию парсинга

На основе того, что выяснили выше опишем data-классами то, что получилось:

Теперь напишем функцию, которая будет парсить поле capabilities:

8. Смотрим результат

Посканирую сеть и покажу, что получилось. Показаны результаты простого вывода через Log.d:

Неосвещенным остался вопрос подключения к сети из кода приложения. Скажу только, что для того, чтобы считать сохраненные пароли ОС мобильного устройства, нужны root-права и готовность порыться в файловой системе чтобы прочитать wpa_supplicant.conf. Если логика приложения предполагает ввод пароля извне, подключение можно осуществить через класс android.net.wifi.WifiManager.

Спасибо Егору Пономареву за ценные дополнения.

Если считаете, что нужно что-то добавить или исправить, пишите в комментарии 🙂

Источник

WifiManager

Class Overview

This class provides the primary API for managing all aspects of Wi-Fi connectivity. Get an instance of this class by calling Context.getSystemService(Context.WIFI_SERVICE) . It deals with several categories of items:

  • The list of configured networks. The list can be viewed and updated, and attributes of individual entries can be modified.
  • The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried.
  • Results of access point scans, containing enough information to make decisions about what access point to connect to.
  • It defines the names of various Intent actions that are broadcast upon any sort of change in Wi-Fi state.

This is the API to use when performing Wi-Fi specific operations. To perform operations that pertain to network connectivity at an abstract level, use ConnectivityManager .

Summary

Nested Classes
WifiManager.MulticastLock Allows an application to receive Wifi Multicast packets.
WifiManager.WifiLock Allows an application to keep the Wi-Fi radio awake.
WifiManager.WpsCallback Interface for callback invocation on a start WPS action
Constants
String ACTION_PICK_WIFI_NETWORK Activity Action: Pick a Wi-Fi network to connect to.
String ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE Activity Action: Show a system activity that allows the user to enable scans to be available even with Wi-Fi turned off.
int ERROR_AUTHENTICATING The error code if there was a problem authenticating.
String EXTRA_BSSID The lookup key for a String giving the BSSID of the access point to which we are connected.
String EXTRA_NETWORK_INFO The lookup key for a NetworkInfo object associated with the Wi-Fi network.
String EXTRA_NEW_RSSI The lookup key for an int giving the new RSSI in dBm.
String EXTRA_NEW_STATE The lookup key for a SupplicantState describing the new state Retrieve with getParcelableExtra(String) .
String EXTRA_PREVIOUS_WIFI_STATE The previous Wi-Fi state.
String EXTRA_RESULTS_UPDATED Lookup key for a boolean representing the result of previous startScan() operation, reported with SCAN_RESULTS_AVAILABLE_ACTION .
String EXTRA_SUPPLICANT_CONNECTED The lookup key for a boolean that indicates whether a connection to the supplicant daemon has been gained or lost.
String EXTRA_SUPPLICANT_ERROR The lookup key for a SupplicantState describing the supplicant error code if any Retrieve with getIntExtra(String, int) .
String EXTRA_WIFI_INFO The lookup key for a WifiInfo object giving the information about the access point to which we are connected.
String EXTRA_WIFI_STATE The lookup key for an int that indicates whether Wi-Fi is enabled, disabled, enabling, disabling, or unknown.
String NETWORK_IDS_CHANGED_ACTION The network IDs of the configured networks could have changed.
String NETWORK_STATE_CHANGED_ACTION Broadcast intent action indicating that the state of Wi-Fi connectivity has changed.
String RSSI_CHANGED_ACTION The RSSI (signal strength) has changed.
String SCAN_RESULTS_AVAILABLE_ACTION An access point scan has completed, and results are available from the supplicant.
String SUPPLICANT_CONNECTION_CHANGE_ACTION Broadcast intent action indicating that a connection to the supplicant has been established (and it is now possible to perform Wi-Fi operations) or the connection to the supplicant has been lost.
String SUPPLICANT_STATE_CHANGED_ACTION Broadcast intent action indicating that the state of establishing a connection to an access point has changed.One extra provides the new SupplicantState .
int WIFI_MODE_FULL In this Wi-Fi lock mode, Wi-Fi will be kept active, and will behave normally, i.e., it will attempt to automatically establish a connection to a remembered access point that is within range, and will do periodic scans if there are remembered access points but none are in range.
int WIFI_MODE_FULL_HIGH_PERF In this Wi-Fi lock mode, Wi-Fi will be kept active as in mode WIFI_MODE_FULL but it operates at high performance with minimum packet loss and low packet latency even when the device screen is off.
int WIFI_MODE_SCAN_ONLY In this Wi-Fi lock mode, Wi-Fi will be kept active, but the only operation that will be supported is initiation of scans, and the subsequent reporting of scan results.
String WIFI_STATE_CHANGED_ACTION Broadcast intent action indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown.
int WIFI_STATE_DISABLED Wi-Fi is disabled.
int WIFI_STATE_DISABLING Wi-Fi is currently being disabled.
int WIFI_STATE_ENABLED Wi-Fi is enabled.
int WIFI_STATE_ENABLING Wi-Fi is currently being enabled.
int WIFI_STATE_UNKNOWN Wi-Fi is in an unknown state.
int WPS_AUTH_FAILURE Authentication failure on WPS
int WPS_OVERLAP_ERROR WPS overlap detected
int WPS_TIMED_OUT WPS timed out
int WPS_TKIP_ONLY_PROHIBITED TKIP only prohibited
int WPS_WEP_PROHIBITED WEP on WPS is prohibited
Public Methods

Constants

public static final String ACTION_PICK_WIFI_NETWORK

Activity Action: Pick a Wi-Fi network to connect to.

public static final String ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE

Activity Action: Show a system activity that allows the user to enable scans to be available even with Wi-Fi turned off.

Notification of the result of this activity is posted using the onActivityResult(int, int, Intent) callback. The resultCode will be RESULT_OK if scan always mode has been turned on or RESULT_CANCELED if the user has rejected the request or an error has occurred.

public static final int ERROR_AUTHENTICATING

The error code if there was a problem authenticating.

public static final String EXTRA_BSSID

The lookup key for a String giving the BSSID of the access point to which we are connected. Only present when the new state is CONNECTED. Retrieve with getStringExtra(String) .

public static final String EXTRA_NETWORK_INFO

The lookup key for a NetworkInfo object associated with the Wi-Fi network. Retrieve with getParcelableExtra(String) .

public static final String EXTRA_NEW_RSSI

The lookup key for an int giving the new RSSI in dBm.

public static final String EXTRA_NEW_STATE

The lookup key for a SupplicantState describing the new state Retrieve with getParcelableExtra(String) .

public static final String EXTRA_PREVIOUS_WIFI_STATE

The previous Wi-Fi state.

See Also

public static final String EXTRA_RESULTS_UPDATED

Lookup key for a boolean representing the result of previous startScan() operation, reported with SCAN_RESULTS_AVAILABLE_ACTION .

public static final String EXTRA_SUPPLICANT_CONNECTED

The lookup key for a boolean that indicates whether a connection to the supplicant daemon has been gained or lost. true means a connection now exists. Retrieve it with getBooleanExtra(String, boolean) .

public static final String EXTRA_SUPPLICANT_ERROR

The lookup key for a SupplicantState describing the supplicant error code if any Retrieve with getIntExtra(String, int) .

See Also

public static final String EXTRA_WIFI_INFO

The lookup key for a WifiInfo object giving the information about the access point to which we are connected. Only present when the new state is CONNECTED. Retrieve with getParcelableExtra(String) .

public static final String EXTRA_WIFI_STATE

The lookup key for an int that indicates whether Wi-Fi is enabled, disabled, enabling, disabling, or unknown. Retrieve it with getIntExtra(String, int) .

See Also

public static final String NETWORK_IDS_CHANGED_ACTION

The network IDs of the configured networks could have changed.

public static final String NETWORK_STATE_CHANGED_ACTION

Broadcast intent action indicating that the state of Wi-Fi connectivity has changed. One extra provides the new state in the form of a NetworkInfo object. If the new state is CONNECTED, additional extras may provide the BSSID and WifiInfo of the access point. as a String .

See Also

public static final String RSSI_CHANGED_ACTION

The RSSI (signal strength) has changed.

See Also

public static final String SCAN_RESULTS_AVAILABLE_ACTION

An access point scan has completed, and results are available from the supplicant. Call getScanResults() to obtain the results. EXTRA_RESULTS_UPDATED indicates if the scan was completed successfully.

public static final String SUPPLICANT_CONNECTION_CHANGE_ACTION

Broadcast intent action indicating that a connection to the supplicant has been established (and it is now possible to perform Wi-Fi operations) or the connection to the supplicant has been lost. One extra provides the connection state as a boolean, where true means CONNECTED.

See Also

public static final String SUPPLICANT_STATE_CHANGED_ACTION

Broadcast intent action indicating that the state of establishing a connection to an access point has changed.One extra provides the new SupplicantState . Note that the supplicant state is Wi-Fi specific, and is not generally the most useful thing to look at if you are just interested in the overall state of connectivity.

See Also

public static final int WIFI_MODE_FULL

In this Wi-Fi lock mode, Wi-Fi will be kept active, and will behave normally, i.e., it will attempt to automatically establish a connection to a remembered access point that is within range, and will do periodic scans if there are remembered access points but none are in range.

public static final int WIFI_MODE_FULL_HIGH_PERF

In this Wi-Fi lock mode, Wi-Fi will be kept active as in mode WIFI_MODE_FULL but it operates at high performance with minimum packet loss and low packet latency even when the device screen is off. This mode will consume more power and hence should be used only when there is a need for such an active connection.

An example use case is when a voice connection needs to be kept active even after the device screen goes off. Holding the regular WIFI_MODE_FULL lock will keep the wifi connection active, but the connection can be lossy. Holding a WIFI_MODE_FULL_HIGH_PERF lock for the duration of the voice call will improve the call quality.

When there is no support from the hardware, this lock mode will have the same behavior as WIFI_MODE_FULL

public static final int WIFI_MODE_SCAN_ONLY

In this Wi-Fi lock mode, Wi-Fi will be kept active, but the only operation that will be supported is initiation of scans, and the subsequent reporting of scan results. No attempts will be made to automatically connect to remembered access points, nor will periodic scans be automatically performed looking for remembered access points. Scans must be explicitly requested by an application in this mode.

public static final String WIFI_STATE_CHANGED_ACTION

Broadcast intent action indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown. One extra provides this state as an int. Another extra provides the previous state, if available.

See Also

public static final int WIFI_STATE_DISABLED

Wi-Fi is disabled.

See Also

public static final int WIFI_STATE_DISABLING

Wi-Fi is currently being disabled. The state will change to WIFI_STATE_DISABLED if it finishes successfully.

See Also

public static final int WIFI_STATE_ENABLED

Wi-Fi is enabled.

See Also

public static final int WIFI_STATE_ENABLING

Wi-Fi is currently being enabled. The state will change to WIFI_STATE_ENABLED if it finishes successfully.

See Also

public static final int WIFI_STATE_UNKNOWN

Wi-Fi is in an unknown state. This state will occur when an error happens while enabling or disabling.

See Also

public static final int WPS_AUTH_FAILURE

Authentication failure on WPS

public static final int WPS_OVERLAP_ERROR

WPS overlap detected

public static final int WPS_TIMED_OUT

public static final int WPS_TKIP_ONLY_PROHIBITED

TKIP only prohibited

public static final int WPS_WEP_PROHIBITED

WEP on WPS is prohibited

Public Methods

public int addNetwork (WifiConfiguration config)

Add a new network description to the set of configured networks. The networkId field of the supplied configuration object is ignored.

The new network will be marked DISABLED by default. To enable it, called enableNetwork(int, boolean) .

Parameters
config the set of variables that describe the configuration, contained in a WifiConfiguration object.
Returns
  • the ID of the newly created network description. This is used in other operations to specified the network to be acted upon. Returns -1 on failure.

public static int calculateSignalLevel (int rssi, int numLevels)

Calculates the level of the signal. This should be used any time a signal is being shown.

Parameters
rssi The power of the signal measured in RSSI.
numLevels The number of levels to consider in the calculated level.
Returns
  • A level of the signal, given in the range of 0 to numLevels-1 (both inclusive).

public void cancelWps (WifiManager.WpsCallback listener)

Cancel any ongoing Wi-fi Protected Setup

Parameters
listener for callbacks on success or failure. Can be null.
Throws
IllegalStateException if the WifiManager instance needs to be initialized again

public static int compareSignalLevel (int rssiA, int rssiB)

Compares two signal strengths.

Parameters
rssiA The power of the first signal measured in RSSI.
rssiB The power of the second signal measured in RSSI.
Returns
  • Returns 0 if the first signal is stronger than the second signal.

public WifiManager.MulticastLock createMulticastLock (String tag)

Create a new MulticastLock

Parameters
tag a tag for the MulticastLock to identify it in debugging messages. This string is never shown to the user under normal conditions, but should be descriptive enough to identify your application and the specific MulticastLock within it, if it holds multiple MulticastLocks.
Returns
  • a new, unacquired MulticastLock with the given tag.
See Also

public WifiManager.WifiLock createWifiLock (String tag)

Creates a new WifiLock.

Parameters
tag a tag for the WifiLock to identify it in debugging messages. This string is never shown to the user under normal conditions, but should be descriptive enough to identify your application and the specific WifiLock within it, if it holds multiple WifiLocks.
Returns
  • a new, unacquired WifiLock with the given tag.
See Also

public WifiManager.WifiLock createWifiLock (int lockType, String tag)

Creates a new WifiLock.

Parameters
lockType the type of lock to create. See WIFI_MODE_FULL , WIFI_MODE_FULL_HIGH_PERF and WIFI_MODE_SCAN_ONLY for descriptions of the types of Wi-Fi locks.
tag a tag for the WifiLock to identify it in debugging messages. This string is never shown to the user under normal conditions, but should be descriptive enough to identify your application and the specific WifiLock within it, if it holds multiple WifiLocks.
Returns
  • a new, unacquired WifiLock with the given tag.
See Also

public boolean disableNetwork (int netId)

Disable a configured network. The specified network will not be a candidate for associating. This may result in the asynchronous delivery of state change events.

Parameters
netId the ID of the network as returned by addNetwork(WifiConfiguration) .
Returns
  • true if the operation succeeded

public boolean disconnect ()

Disassociate from the currently active access point. This may result in the asynchronous delivery of state change events.

Returns
  • true if the operation succeeded

public boolean enableNetwork (int netId, boolean disableOthers)

Allow a previously configured network to be associated with. If disableOthers is true, then all other configured networks are disabled, and an attempt to connect to the selected network is initiated. This may result in the asynchronous delivery of state change events.

Note: If an application’s target SDK version is LOLLIPOP or newer, network communication may not use Wi-Fi even if Wi-Fi is connected; traffic may instead be sent through another network, such as cellular data, Bluetooth tethering, or Ethernet. For example, traffic will never use a Wi-Fi network that does not provide Internet access (e.g. a wireless printer), if another network that does offer Internet access (e.g. cellular data) is available. Applications that need to ensure that their network traffic uses Wi-Fi should use APIs such as bindSocket(java.net.Socket) , openConnection(java.net.URL) , or bindProcessToNetwork(Network) to do so.

Parameters
netId the ID of the network in the list of configured networks
disableOthers if true, disable all other networks. The way to select a particular network to connect to is specify true for this parameter.
Returns
  • true if the operation succeeded

public List getConfiguredNetworks ()

Return a list of all the networks configured in the supplicant. Not all fields of WifiConfiguration are returned. Only the following fields are filled in:

  • networkId
  • SSID
  • BSSID
  • priority
  • allowedProtocols
  • allowedKeyManagement
  • allowedAuthAlgorithms
  • allowedPairwiseCiphers
  • allowedGroupCiphers
Returns
  • a list of network configurations in the form of a list of WifiConfiguration objects. Upon failure to fetch or when when Wi-Fi is turned off, it can be null.

public WifiInfo getConnectionInfo ()

Return dynamic information about the current Wi-Fi connection, if any is active.

Returns
  • the Wi-Fi information, contained in WifiInfo .

public DhcpInfo getDhcpInfo ()

Return the DHCP-assigned addresses from the last successful DHCP request, if any.

Returns

public List getScanResults ()

Return the results of the latest access point scan.

Returns
  • the list of access points found in the most recent scan. An app must hold ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission in order to get valid results.

public int getWifiState ()

Gets the Wi-Fi enabled state.

Returns
See Also

public boolean is5GHzBandSupported ()

Returns
  • true if this adapter supports 5 GHz band

public boolean isDeviceToApRttSupported ()

Returns
  • true if this adapter supports Device-to-AP RTT

public boolean isEnhancedPowerReportingSupported ()

Returns
  • true if this adapter supports advanced power/performance counters

public boolean isP2pSupported ()

Returns
  • true if this adapter supports WifiP2pManager (Wi-Fi Direct)

public boolean isPreferredNetworkOffloadSupported ()

Returns
  • true if this adapter supports offloaded connectivity scan

public boolean isScanAlwaysAvailable ()

Check if scanning is always available. If this return true , apps can issue startScan() and fetch scan results even when Wi-Fi is turned off. To change this setting, see ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE .

public boolean isTdlsSupported ()

Returns
  • true if this adapter supports Tunnel Directed Link Setup

public boolean isWifiEnabled ()

Return whether Wi-Fi is enabled or disabled.

Returns
See Also

public boolean pingSupplicant ()

Check that the supplicant daemon is responding to requests.

Returns
  • true if we were able to communicate with the supplicant and it returned the expected response to the PING message.

public boolean reassociate ()

Reconnect to the currently active access point, even if we are already connected. This may result in the asynchronous delivery of state change events.

Returns
  • true if the operation succeeded

public boolean reconnect ()

Reconnect to the currently active access point, if we are currently disconnected. This may result in the asynchronous delivery of state change events.

Returns
  • true if the operation succeeded

public boolean removeNetwork (int netId)

Remove the specified network from the list of configured networks. This may result in the asynchronous delivery of state change events.

Parameters
netId the integer that identifies the network configuration to the supplicant
Returns
  • true if the operation succeeded

public boolean saveConfiguration ()

Tell the supplicant to persist the current list of configured networks.

Note: It is possible for this method to change the network IDs of existing networks. You should assume the network IDs can be different after calling this method.

Returns
  • true if the operation succeeded

public void setTdlsEnabled (InetAddress remoteIPAddress, boolean enable)

Enable/Disable TDLS on a specific local route.

TDLS enables two wireless endpoints to talk to each other directly without going through the access point that is managing the local network. It saves bandwidth and improves quality of the link.

This API enables/disables the option of using TDLS. If enabled, the underlying hardware is free to use TDLS or a hop through the access point. If disabled, existing TDLS session is torn down and hardware is restricted to use access point for transferring wireless packets. Default value for all routes is ‘disabled’, meaning restricted to use access point for transferring packets.

Parameters
remoteIPAddress IP address of the endpoint to setup TDLS with
enable true = setup and false = tear down TDLS

public void setTdlsEnabledWithMacAddress (String remoteMacAddress, boolean enable)

Similar to setTdlsEnabled(InetAddress, boolean) , except this version allows you to specify remote endpoint with a MAC address.

Parameters
remoteMacAddress MAC address of the remote endpoint such as 00:00:0c:9f:f2:ab
enable true = setup and false = tear down TDLS

public boolean setWifiEnabled (boolean enabled)

Enable or disable Wi-Fi.

Parameters
enabled true to enable, false to disable.
Returns
  • true if the operation succeeds (or if the existing state is the same as the requested state).

public boolean startScan ()

Request a scan for access points. Returns immediately. The availability of the results is made known later by means of an asynchronous event sent on completion of the scan.

Returns
  • true if the operation succeeded, i.e., the scan was initiated

public void startWps (WpsInfo config, WifiManager.WpsCallback listener)

Start Wi-fi Protected Setup

Parameters
config WPS configuration (does not support LABEL )
listener for callbacks on success or failure. Can be null.
Throws
IllegalStateException if the WifiManager instance needs to be initialized again

public int updateNetwork (WifiConfiguration config)

Update the network description of an existing configured network.

Parameters
config the set of variables that describe the configuration, contained in a WifiConfiguration object. It may be sparse, so that only the items that are being changed are non- null . The networkId field must be set to the ID of the existing network being updated.
Returns
  • Returns the networkId of the supplied WifiConfiguration on success.
    Returns -1 on failure, including when the networkId field of the WifiConfiguration does not refer to an existing network.

Protected Methods

protected void finalize ()

Invoked when the garbage collector has detected that this instance is no longer reachable. The default implementation does nothing, but this method can be overridden to free resources.

Note that objects that override finalize are significantly more expensive than objects that don’t. Finalizers may be run a long time after the object is no longer reachable, depending on memory pressure, so it’s a bad idea to rely on them for cleanup. Note also that finalizers are run on a single VM-wide finalizer thread, so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary for a class that has a native peer and needs to call a native method to destroy that peer. Even then, it’s better to provide an explicit close method (and implement Closeable ), and insist that callers manually dispose of instances. This works well for something like files, but less well for something like a BigInteger where typical calling code would have to deal with lots of temporaries. Unfortunately, code that creates lots of temporaries is the worst kind of code from the point of view of the single finalizer thread.

If you must use finalizers, consider at least providing your own ReferenceQueue and having your own thread process that queue.

Unlike constructors, finalizers are not automatically chained. You are responsible for calling super.finalize() yourself.

Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer thread. See Effective Java Item 7, «Avoid finalizers» for more.

Источник

Читайте также:  Как удалить графический пароль с андроида
Оцените статью