Wifi Manager Class
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
This class provides the primary API for managing all aspects of Wi-Fi connectivity.
[Android.Runtime.Register("android/net/wifi/WifiManager", DoNotGenerateAcw=true)] public class WifiManager : Java.Lang.Object
[] type WifiManager = class inherit Object
Remarks
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Constructors
A constructor used when creating managed representations of JNI objects; called by the runtime.
Fields
Activity Action: Pick a Wi-Fi network to connect to.
Activity Action: Show a system activity that allows the user to enable scans to be available even with Wi-Fi turned off.
The error code if there was a problem authenticating.
The lookup key for a String giving the BSSID of the access point to which we are connected.
The lookup key for a NetworkInfo object associated with the Wi-Fi network.
The lookup key for an int giving the new RSSI in dBm.
The lookup key for a SupplicantState describing the new state Retrieve with GetParcelableExtra(String).
The lookup key for a boolean that indicates whether a connection to the supplicant daemon has been gained or lost.
The lookup key for a SupplicantState describing the supplicant error code if any Retrieve with GetIntExtra(String, Int32).
The lookup key for a WifiInfo object giving the information about the access point to which we are connected.
The lookup key for an int that indicates whether Wi-Fi is enabled, disabled, enabling, disabling, or unknown.
The network IDs of the configured networks could have changed.
Broadcast intent action indicating that the state of Wi-Fi connectivity has changed.
The RSSI (signal strength) has changed.
An access point scan has completed, and results are available from the supplicant.
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.
Broadcast intent action indicating that the state of establishing a connection to an access point has changed.
Broadcast intent action indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown.
Properties
Returns the runtime class of this Object .
Return a list of all the networks configured in the supplicant.
Return dynamic information about the current Wi-Fi connection, if any is active.
Return the DHCP-assigned addresses from the last successful DHCP request, if any.
The handle to the underlying Android instance.
Check if scanning is always available.
Return whether Wi-Fi is enabled or disabled.
Return the results of the latest access point scan.
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
Gets the Wi-Fi enabled state.
Methods
Add a new network description to the set of configured networks.
Calculates the level of the signal.
Cancel any ongoing Wi-fi Protected Setup
Creates and returns a copy of this object.
Compares two signal strengths.
Create a new MulticastLock
Disable a configured network.
Disassociate from the currently active access point.
Allow a previously configured network to be associated with.
Indicates whether some other object is «equal to» this one.
Returns a hash code value for the object.
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
Wakes up a single thread that is waiting on this object’s monitor.
Wakes up all threads that are waiting on this object’s monitor.
Check that the supplicant daemon is responding to requests.
Reconnect to the currently active access point, even if we are already connected.
Reconnect to the currently active access point, if we are currently disconnected.
Remove the specified network from the list of configured networks.
Tell the supplicant to persist the current list of configured networks.
Enable/Disable TDLS on a specific local route.
Similar to SetTdlsEnabled(InetAddress, Boolean), except this version allows you to specify remote endpoint with a MAC address.
Request a scan for access points.
Start Wi-fi Protected Setup
Returns a string representation of the object.
Update the network description of an existing configured network.
Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.
Causes the current thread to wait until either another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object, or a specified amount of time has elapsed.
Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
Explicit Interface Implementations
IJavaPeerable.Disposed() | (Inherited from Object) |
IJavaPeerable.DisposeUnlessReferenced() | (Inherited from Object) |
IJavaPeerable.Finalized() | (Inherited from Object) |
IJavaPeerable.JniManagedPeerState | (Inherited from Object) |
IJavaPeerable.SetJniIdentityHashCode(Int32) | (Inherited from Object) |
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) | (Inherited from Object) |
IJavaPeerable.SetPeerReference(JniObjectReference) | (Inherited from Object) |
Extension Methods
Performs an Android runtime-checked type conversion.
Руководство Android Wifi Scanning
Следуйте за нами на нашей фан-странице, чтобы получать уведомления каждый раз, когда появляются новые статьи. Facebook
1- Android Wi-Fi
В Android, Wi-Fi это протокол беспроводной передачи (Wireless Network Protocol), позволяет устройствам подключиться к Internet (интернету) или подключение устройств друг к другу для обмена данных.
Точнее, Android предоставляет Wi-Fi API, приложения могут использовать данный API для управления всех аспектов связанных с подключением к Wifi, например поиск текущих сетей Wifi, добавить, сохранить, удалить сети Wifi и управлять обменявшимися данными между устройствами.
- Сканировать (scan) для поиска готовых сетей Wifi в диапазоне.
- Позволить устройству подключиться к Internet.
- Подключить к другим устройствам через Service Discovery (Обнаружение сервисов).
- Управлять списком конфигурированных сетей.
- Управлять многими подключениями.
Начиная с Android 10.0 (API Level 29) вы не можете использовать Wi-Fi API чтобы включить/выключить (enable/disable) Wifi системы, это значит если вы хотите включить/выключить Wifi, вам нужно использовать готовые функции операционной системы.
Политика конфиденциальности для использования Wi-Fi API чтобы включить/выключить Wifi была изменена через многие версии Android. Точнее:
Android Level | Политика конфиденциальности |
Level 1 ==> Level 22 (Android < 6.0) | Нужно добавить android.permission.CHANGE_WIFI_STATE в AndroidManifest.xml. |
Level 23 ==> Level 28 (Android 6.0 — 9.x) | Нужно добавить android.permission.CHANGE_WIFI_STATE в AndroidManifest.xml, одновременно, ваше приложение должно спросить разрешение пользователя, чтобы включить/выключить Wifi системы. |
Level 29+ (Android 10.0+) | Не разрешать использовать Wi-Fi API, чтобы включить/выключить Wifi системы. |
WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(true); // Enable Wifi wifiManager.setWifiEnabled(false); // Disable Wifi
В Android 10+ (API Level 29+), метод setWifiEnabled(boolean) больше не работает.
Чтобы получить статус Wifi, вам нужно добавить android.permission.ACCESS_WIFI_STATE в AndroidManifest.xml:
WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE); int state = wifiManager.getWifiState(); String statusInfo = "Unknown"; switch (state)
WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE); // Get List of Available Wifi Networks List availNetworks = wifiManager.getScanResults(); if (availNetworks.size() > 0) < // Get Each network detail for (int i=0; i< availNetworks.size();i++) < // . >>
Политика конфиденциальности для сканирования (scan) текущих сетей так же была изменена через разные версии Android:
Android API Level | Политика конфиденциальности |
Level 1 ==> Level 22 (Android < 6.0) | Нужно добавить android.permission.ACCESS_COARSE_LOCATION в AndroidManifest.xml. |
Level 23+ (Android 6.0+) | Нужно добавить android.permission.ACCESS_COARSE_LOCATION в AndroidManifest.xml, одновременно ваше приложение должно спросить разрешение пользователся сканировать (scan) текущие сети. |
2- Пример WifiManager
В данном примере я покажу вам как использовать WifiManager, чтобы получить статус Wifi, сканировать текущие сети, записать детальную информацию каждой найденной сети и подключить к определенной сети в списке.
- File > New > New Project > Empty Activity
- Name: WifiManagerExample
- Package name: org.o7planning.wifimanagerexample
- Language: Java
package org.o7planning.wifimanagerexample; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.util.List; public class MainActivity extends AppCompatActivity < private static final String LOG_TAG = "AndroidExample"; private static final int MY_REQUEST_CODE = 123; private WifiManager wifiManager; private Button buttonState; private Button buttonScan; private EditText editTextPassword; private LinearLayout linearLayoutScanResults; private TextView textViewScanResults; private WifiBroadcastReceiver wifiReceiver; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); // Instantiate broadcast receiver this.wifiReceiver = new WifiBroadcastReceiver(); // Register the receiver registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); // this.buttonState = (Button) this.findViewById(R.id.button_state); this.buttonScan = (Button) this.findViewById(R.id.button_scan); this.editTextPassword = (EditText) this.findViewById(R.id.editText_password); this.textViewScanResults = (TextView) this.findViewById(R.id.textView_scanResults); this.linearLayoutScanResults = (LinearLayout) this.findViewById(R.id.linearLayout_scanResults); this.buttonState.setOnClickListener(new View.OnClickListener()< @Override public void onClick(View v) < showWifiState(); >>); this.buttonScan.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < askAndStartScanWifi(); >>); > private void askAndStartScanWifi() < // With Android Level >= 23, you have to ask the user // for permission to Call. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) < // 23 int permission1 = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION); // Check for permissions if (permission1 != PackageManager.PERMISSION_GRANTED) < Log.d(LOG_TAG, "Requesting Permissions"); // Request permissions ActivityCompat.requestPermissions(this, new String[] < Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_NETWORK_STATE >, MY_REQUEST_CODE); return; > Log.d(LOG_TAG, "Permissions Already Granted"); > this.doStartScanWifi(); > private void doStartScanWifi() < this.wifiManager.startScan(); >@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) < Log.d(LOG_TAG, "onRequestPermissionsResult"); switch (requestCode) < case MY_REQUEST_CODE: < // If request is cancelled, the result arrays are empty. if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) < // permission was granted Log.d(LOG_TAG, "Permission Granted: " + permissions[0]); // Start Scan Wifi. this.doStartScanWifi(); >else < // Permission denied, boo! Disable the // functionality that depends on this permission. Log.d(LOG_TAG, "Permission Denied: " + permissions[0]); >break; > // Other 'case' lines to check for other // permissions this app might request. > > private void showWifiState() < int state = this.wifiManager.getWifiState(); String statusInfo = "Unknown"; switch (state) < case WifiManager.WIFI_STATE_DISABLING: statusInfo = "Disabling"; break; case WifiManager.WIFI_STATE_DISABLED: statusInfo = "Disabled"; break; case WifiManager.WIFI_STATE_ENABLING: statusInfo = "Enabling"; break; case WifiManager.WIFI_STATE_ENABLED: statusInfo = "Enabled"; break; case WifiManager.WIFI_STATE_UNKNOWN: statusInfo = "Unknown"; break; default: statusInfo = "Unknown"; break; >Toast.makeText(this, "Wifi Status: " + statusInfo, Toast.LENGTH_LONG).show(); > @Override protected void onStop() < this.unregisterReceiver(this.wifiReceiver); super.onStop(); >// Define class to listen to broadcasts class WifiBroadcastReceiver extends BroadcastReceiver < @Override public void onReceive(Context context, Intent intent) < Log.d(LOG_TAG, "onReceive()"); Toast.makeText(MainActivity.this, "Scan Complete!", Toast.LENGTH_SHORT).show(); boolean ok = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false); if (ok) < Log.d(LOG_TAG, "Scan OK"); Listlist = wifiManager.getScanResults(); MainActivity.this.showNetworks(list); MainActivity.this.showNetworksDetails(list); > else < Log.d(LOG_TAG, "Scan not OK"); >> > private void showNetworks(List results) < this.linearLayoutScanResults.removeAllViews(); for( final ScanResult result: results) < final String networkCapabilities = result.capabilities; final String networkSSID = result.SSID; // Network Name. // Button button = new Button(this ); button.setText(networkSSID + " ("+networkCapabilities+")"); this.linearLayoutScanResults.addView(button); button.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < String networkCapabilities = result.capabilities; connectToNetwork(networkCapabilities, networkSSID); >>); > > private void showNetworksDetails(List results) < this.textViewScanResults.setText(""); StringBuilder sb = new StringBuilder(); sb.append("Result Count: " + results.size()); for(int i = 0; i < results.size(); i++ ) < ScanResult result = results.get(i); sb.append("\n\n --------- Network " + i + "/" + results.size() + " ---------"); sb.append("\n result.capabilities: " + result.capabilities); sb.append("\n result.SSID: " + result.SSID); // Network Name. sb.append("\n result.BSSID: " + result.BSSID); sb.append("\n result.frequency: " + result.frequency); sb.append("\n result.level: " + result.level); sb.append("\n result.describeContents(): " + result.describeContents()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) < // Level 17, Android 4.2 sb.append("\n result.timestamp: " + result.timestamp); >if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < // Level 23, Android 6.0 sb.append("\n result.centerFreq0: " + result.centerFreq0); sb.append("\n result.centerFreq1: " + result.centerFreq1); sb.append("\n result.venueName: " + result.venueName); sb.append("\n result.operatorFriendlyName: " + result.operatorFriendlyName); sb.append("\n result.channelWidth: " + result.channelWidth); sb.append("\n result.is80211mcResponder(): " + result.is80211mcResponder()); sb.append("\n result.isPasspointNetwork(): " + result.isPasspointNetwork() ); >> this.textViewScanResults.setText(sb.toString()); > private void connectToNetwork(String networkCapabilities, String networkSSID) < Toast.makeText(this, "Connecting to network: "+ networkSSID, Toast.LENGTH_SHORT).show(); String networkPass = this.editTextPassword.getText().toString(); // WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = "\"" + networkSSID + "\""; if(networkCapabilities.toUpperCase().contains("WEP")) < // WEP Network. Toast.makeText(this, "WEP Network", Toast.LENGTH_SHORT).show(); wifiConfig.wepKeys[0] = "\"" + networkPass + "\""; wifiConfig.wepTxKeyIndex = 0; wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); >else if(networkCapabilities.toUpperCase().contains("WPA")) < // WPA Network Toast.makeText(this, "WPA Network", Toast.LENGTH_SHORT).show(); wifiConfig.preSharedKey = "\""+ networkPass +"\""; >else < // OPEN Network. Toast.makeText(this, "OPEN Network", Toast.LENGTH_SHORT).show(); wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); >this.wifiManager.addNetwork(wifiConfig); List list = this.wifiManager.getConfiguredNetworks(); for( WifiConfiguration config : list ) < if(config.SSID != null && config.SSID.equals("\"" + networkSSID + "\"")) < this.wifiManager.disconnect(); this. wifiManager.enableNetwork(config.networkId, true); this.wifiManager.reconnect(); break; >> > >
View more Tutorials:
Это онлайн курс вне вебсайта o7planning, который мы представляем, он включает бесплатные курсы или курсы со скидкой.
- Android Beginners Guide To Create A Weather Forecast App
- * * The Complete Android Oreo(8.1) , N ,M and Java Development
- Absolute Java Basics for Android
- Android App & Game Development :Build 6 Android Apps & Games
- Android and iOS Apps for Your WordPress Blog
- Unity 3d Game Development — iOS, Android, & Web — Beginners
- Learn Android Development From Scratch
- Ultimate Coding Course for Web App and Android Development
- Unity Android Game Development : Build 7 2D & 3D Games
- The Complete Android™ Material Design Course
- Publish Games on Android, iTunes, and Google Play with UE4
- Advance Android Programming — learning beyond basics
- The Android Crash Course For Beginners to Advanced
- Learning Path:Android:Application Development with Android N
- Android development quick start for beginners
- Developing High Quality Android Applications
- Android App Development and Design
- Become an iOS/Android Game Developer with Unity 2017
- Learning Path: Android: App Development with Android N
- The Complete Android & Java Developer Course — Build 21 Apps
- The Complete Android App Development
- Create Android & iOS Apps Without Coding
- Develop Your First 2D Game With Unity3D for Android
- Full Stack Mobile Developer course ( iOS 11, and Android O )
- Android Internals and Working with the source