Get wifi info android

How to get current Wi-Fi network id in android?

This example demonstrates How to get current Wi-Fi network id in android.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

In the above code, we have taken text view to show WIFI network id.

Step 3 − Add the following code to src/MainActivity.java

package com.example.myapplication; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.text.format.Formatter; import android.widget.TextView; public class MainActivity extends AppCompatActivity < TextView textView; @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); textView.setText("" + wifiInfo.getNetworkId()); >@Override protected void onStop() < super.onStop(); >@Override protected void onResume() < super.onResume(); >>

Step 4 − Add the following code to androidManifest.xml

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –

Click here to download the project code

Источник

How to get name of wifi-network out of android using android API?

I thought that I should use NetworkInterface::getDisplayName. I got some name, but this name is different that this name which I can see, when I choosing to which network I want to connect.

4 Answers 4

WifiManager wifiMgr = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); String name = wifiInfo.getSSID(); 
public String getWifiName(Context context) < WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (manager.isWifiEnabled()) < WifiInfo wifiInfo = manager.getConnectionInfo(); if (wifiInfo != null) < DetailedState state = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()); if (state == DetailedState.CONNECTED || state == DetailedState.OBTAINING_IPADDR) < return wifiInfo.getSSID(); >> > return null; > 

This (mix and match of various answers from Marakana and others) will simultaneously get everything you want to extract from:

  1. all wifi routers in range
  2. connected wifi router
  3. all stored wifi networks (on your device)
public String getCurrentSsid(Context context) < String ssid = null; ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (networkInfo.isConnected()) < final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); final WifiInfo connectionInfo = wifiManager.getConnectionInfo(); if (connectionInfo != null && !(connectionInfo.getSSID().equals(""))) < //if (connectionInfo != null && !StringUtil.isBlank(connectionInfo.getSSID())) < ssid = connectionInfo.getSSID(); >// Get WiFi status MARAKANA WifiInfo info = wifiManager.getConnectionInfo(); String textStatus = ""; textStatus += "\n\nWiFi Status: " + info.toString(); String BSSID = info.getBSSID(); String MAC = info.getMacAddress(); List results = wifiManager.getScanResults(); ScanResult bestSignal = null; int count = 1; String etWifiList = ""; for (ScanResult result : results) < etWifiList += count++ + ". " + result.SSID + " : " + result.level + "\n" + result.BSSID + "\n" + result.capabilities +"\n" + "\n=======================\n"; >Log.v(TAG, "from SO: \n"+etWifiList); // List stored networks List configs = wifiManager.getConfiguredNetworks(); for (WifiConfiguration config : configs) < textStatus+= "\n\n" + config.toString(); >Log.v(TAG,"from marakana: \n"+textStatus); > return ssid; > 

DISCLAIMER: while this is working code, not pseudo code, its only purpose is to illustrate the methods for data extraction from wifi connections and it should be adapted (and cleaned) before use.

Источник

how to get current wifi connection info in android

I have no problem with getting scanresult. I’m always getting the currentWifi null. Where am I doing wrong or is there any alternative method to do this?

3 Answers 3

Most probably you have already found answer: currentWifi.getSSID() is quoted in most cases where scanResult.SSID is not (and of course you must not use == on strings :)).

Try something like this, it returns current SSID or null :

public static String getCurrentSsid(Context context) < String ssid = null; ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (networkInfo.isConnected()) < final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); final WifiInfo connectionInfo = wifiManager.getConnectionInfo(); if (connectionInfo != null && !StringUtil.isBlank(connectionInfo.getSSID())) < ssid = connectionInfo.getSSID(); >> return ssid; > 

also permissions are required:

StringUtil is not a standard Android class, so you can use TextUtils instead. The code then looks like this:

public static String getCurrentSsid(Context context) < String ssid = null; ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (networkInfo.isConnected()) < final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); final WifiInfo connectionInfo = wifiManager.getConnectionInfo(); if (connectionInfo != null && !TextUtils.isEmpty(connectionInfo.getSSID())) < ssid = connectionInfo.getSSID(); >> return ssid; > 

Источник

How do I see if Wi-Fi is connected on Android?

I don’t want my user to even try downloading something unless they have Wi-Fi connected. However, I can only seem to be able to tell if Wi-Fi is enabled, but they could still have a 3G connection.

android.net.wifi.WifiManager m = (WifiManager) getSystemService(WIFI_SERVICE); android.net.wifi.SupplicantState s = m.getConnectionInfo().getSupplicantState(); NetworkInfo.DetailedState state = WifiInfo.getDetailedStateOf(s); if (state != NetworkInfo.DetailedState.CONNECTED)

However, the state is not what I would expect. Even though Wi-Fi is connected, I am getting OBTAINING_IPADDR as the state.

24 Answers 24

You should be able to use the ConnectivityManager to get the state of the Wi-Fi adapter. From there you can check if it is connected or even available.

ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (mWifi.isConnected()) < // Do whatever >

NOTE: It should be noted (for us n00bies here) that you need to add

AndroidManifest.xml for this to work.

This method was deprecated in API level 23. This method does not support multiple connected networks of the same type. Use getAllNetworks() and getNetworkInfo(android.net.Network) instead.

NOTE3: public static final int TYPE_WIFI is now deprecated:

This constant was deprecated in API level 28. Applications should instead use NetworkCapabilities.hasTransport(int) or requestNetwork(NetworkRequest, NetworkCallback) to request an appropriate network. for supported transports.

It should be noted (for us noobies here) that you need to add android.permission.ACCESS_NETWORK_STATE to your AndroidManifest.xml for this to work.

In very recent versions of Android, you need to check for NULL in mWiFi . your code here could throw a null pointer error. See developer.android.com/training/basics/network-ops/managing.html and in particular «The method getActiveNetworkInfo() returns a NetworkInfo. «

It worked for me with Ethernet interface as well. I just changed to ConnectivityManager.TYPE_ETHERNET

NetworkInfo.getType() and ConnectivityManager.TYPE_WIFI are now deprecated in API 28. To avoid lint warning you should use something like connectivityManager.getNetworkCapabilities(network).hasTransport(NetworkCapabilities.TRANSPORT_WIFI)

Since the method NetworkInfo.isConnected() is now deprecated in API-23, here is a method which detects if the Wi-Fi adapter is on and also connected to an access point using WifiManager instead:

private boolean checkWifiOnAndConnected() < WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (wifiMgr.isWifiEnabled()) < // Wi-Fi adapter is ON WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); if( wifiInfo.getNetworkId() == -1 )< return false; // Not connected to an access point >return true; // Connected to an access point > else < return false; // Wi-Fi adapter is OFF >> 

It’s worth mentioning that wifiInfo can be null so I think you should check for null before getting network id

This will no longer work in Android Q without location permission and location mode turned on, see issuetracker.google.com/issues/136021574.

I simply use the following:

SupplicantState supState; wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); supState = wifiInfo.getSupplicantState(); 

Which will return one of these states at the time you call getSupplicantState();

ASSOCIATED — Association completed.

ASSOCIATING — Trying to associate with an access point.

COMPLETED — All authentication completed.

DISCONNECTED — This state indicates that client is not associated, but is likely to start looking for an access point.

DORMANT — An Android-added state that is reported when a client issues an explicit DISCONNECT command.

FOUR_WAY_HANDSHAKE — WPA 4-Way Key Handshake in progress.

GROUP_HANDSHAKE — WPA Group Key Handshake in progress.

INACTIVE — Inactive state.

INVALID — A pseudo-state that should normally never be seen.

SCANNING — Scanning for a network.

UNINITIALIZED — No connection.

hi Donal.I have used the same way to get whether our device is connected to wifi.But additionally i need to know the App name currently using WIFI.How can that b done?

@AbhishekB, sorry but I don’t have any experience with that, perhaps try looking at some of the Wi-Fi monitoring apps, see if there is an open source one where you can review the code.

I’m suspicious of this solution because the supplicant is only used if WPA (or some variation of WPA) is usesd: if user connects to an AP with no authentication or WEP then the supplicant is not involved.

I am using this in my apps to check if the active network is Wi-Fi:

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) < // Do your work here >

This is the best answer because it makes sure that the active network (the one that will be used for downloading) is WiFi

Best solution also in 2020 now that Android Q requests location permissions for some of the solutions in this post. This works without needing location permissions.

I had a look at a few questions like this and came up with this:

ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobile = connManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (wifi.isConnected()) < // If Wi-Fi connected >if (mobile.isConnected()) < // If Internet connected >

I use if for my license check in Root Toolbox PRO, and it seems to work great.

looks good but I’m not sure why you get a second reference to ConnectivityManager. In this example connManager and connManager1 are both the same Object

It is worth bearing in mind, that getNetworkInfo() will return a null, if the network doesn’t exist. So if the device has no mobile connection, this will throw an error. In most cases, TYPE_ETHERNET will cause a null in this case, since most devices will not have an Ethernet connection.

The NetworkInfo class is deprecated as of API level 29, along with the related access methods like ConnectivityManager#getNetworkInfo() and ConnectivityManager#getActiveNetworkInfo() .

The documentation now suggests people to use the ConnectivityManager.NetworkCallback API for asynchronized callback monitoring, or use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties for synchronized access of network information

Callers should instead use the ConnectivityManager.NetworkCallback API to learn about connectivity changes, or switch to use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties to get information synchronously.

To check if WiFi is connected, here’s the code that I use:

val connMgr = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager? connMgr?: return false if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < val network: Network = connMgr.activeNetwork ?: return false val capabilities = connMgr.getNetworkCapabilities(network) return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) >else
ConnectivityManager connMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); if (connMgr == null) < return false; >if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < Network network = connMgr.getActiveNetwork(); if (network == null) return false; NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network); return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI); >else

Remember to also add permission ACCESS_NETWORK_STATE to your Manifest file.

While Jason’s answer is correct, nowadays getNetWorkInfo (int) is a deprecated method. So, the next function would be a nice alternative:

public static boolean isWifiAvailable (Context context)

Many of answers use deprecated code, or code available on higer API versions. Now I use something like this

ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if(connectivityManager != null) < for (Network net : connectivityManager.getAllNetworks()) < NetworkCapabilities nc = connectivityManager.getNetworkCapabilities(net); if (nc != null && nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) return true; >> return false; 

The following code (in Kotlin) works from API 21 until at least current API version (API 29). The function getWifiState() returns one of 3 possible values for the WiFi network state: Disable, EnabledNotConnected and Connected that were defined in an enum class. This allows to take more granular decisions like informing the user to enable WiFi or, if already enabled, to connect to one of the available networks. But if all that is needed is a boolean indicating if the WiFi interface is connected to a network, then the other function isWifiConnected() will give you that. It uses the previous one and compares the result to Connected.

It’s inspired in some of the previous answers but trying to solve the problems introduced by the evolution of Android API’s or the slowly increasing availability of IP V6. The trick was to use:

wifiManager.connectionInfo.bssid != null 
  1. getIpAddress() == 0 that is only valid for IP V4 or
  2. getNetworkId() == -1 that now requires another special permission (Location)

According to the documentation: https://developer.android.com/reference/kotlin/android/net/wifi/WifiInfo.html#getbssid it will return null if not connected to a network. And even if we do not have permission to get the real value, it will still return something other than null if we are connected.

Also have the following in mind:

On releases before android.os.Build.VERSION_CODES#N, this object should only be obtained from an Context#getApplicationContext(), and not from any other derived context to avoid memory leaks within the calling process.

In the Manifest, do not forget to add:

class MyViewModel(application: Application) : AndroidViewModel(application) < // Get application context private val myAppContext: Context = getApplication().applicationContext // Define the different possible states for the WiFi Connection internal enum class WifiState < Disabled, // WiFi is not enabled EnabledNotConnected, // WiFi is enabled but we are not connected to any WiFi network Connected, // Connected to a WiFi network >// Get the current state of the WiFi network private fun getWifiState() : WifiState < val wifiManager : WifiManager = myAppContext.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager return if (wifiManager.isWifiEnabled) < if (wifiManager.connectionInfo.bssid != null) WifiState.Connected else WifiState.EnabledNotConnected >else < WifiState.Disabled >> // Returns true if we are connected to a WiFi network private fun isWiFiConnected() : Boolean < return (getWifiState() == WifiState.Connected) >> 

Источник

Читайте также:  Смартфон сам отключает wifi
Оцените статью
Adblock
detector