how to check slow network connection in android - android

I have to show a page if network connection is slow
iam checking the network by using this code
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
Toast.makeText(MainActivity.this,"wifi",Toast.LENGTH_LONG).show();
// do something
} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
// check NetworkInfo subtype
if (info.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS) {
Toast.makeText(MainActivity.this,"mobile 100kbps",Toast.LENGTH_LONG).show();
// Bandwidth between 100 kbps and below
} else if (info.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE) {
Toast.makeText(MainActivity.this,"mobile 50-100kbps",Toast.LENGTH_LONG).show();
// Bandwidth between 50-100 kbps
} else if (info.getSubtype() == TelephonyManager.NETWORK_TYPE_EVDO_0) {
Toast.makeText(MainActivity.this,"mobile 400-1000kbps",Toast.LENGTH_LONG).show();
// Bandwidth between 400-1000 kbps
} else if (info.getSubtype() == TelephonyManager.NETWORK_TYPE_EVDO_A) {
Toast.makeText(MainActivity.this,"mobile 600-1400kbps",Toast.LENGTH_LONG).show();
// Bandwidth between 600-1400 kbps
}
it is showing the wifi network
But i need the code for slow wifi network.
Please help me is there any code to check slow wifi network.

Use below method to check the wifi level:
public int getWifiLevel()
{
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int linkSpeed = wifiManager.getConnectionInfo().getRssi();
int level = WifiManager.calculateSignalLevel(linkSpeed, 5);
return level;
}
Based on wifi level or link speed you can decide if it has the low connection or high connection internet.

You can use following code for checking wifi speed
WifiManager wifiManager = Context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo != null) {
Integer linkSpeed = wifiInfo.getLinkSpeed(); //measured using WifiInfo.LINK_SPEED_UNITS
}
I hope this may helps you.

Related

How check if current network connected is WIFI 5G?

I have used this approach to check type of current connected network and works fine, except when is connected to WIFI 5G. How know if WIFI network connected is 5G? i only found how check if device supports WIFI 5G. Thanks in advance.
A possible solution is determine based in WIFI frequency, eg:
private static boolean is24GHzWifi(int frequency) {
return frequency > 2400 && frequency < 2500;
}
private static boolean is5GHzWifi(int frequency) {
return frequency > 4900 && frequency < 5900;
}
// ...
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
WifiManager wifiMgr = (WifiManager) getContext().getSystemService(context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int frequency = wifiInfo.getFrequency();
if (is24GHzWifi(frequency))
return "WIFI 2.4G";
else if (is5GHzWifi(frequency))
return "WIFI 5G";
else
return "WIFI";
}
Reference: Android judge whether wifi is 2.4G or 5G

Cannot get android app to detect wifi connections [duplicate]

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) {
return false;
}
However, the state is not what I would expect. Even though Wi-Fi is connected, I am getting OBTAINING_IPADDR as the state.
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
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
to your
AndroidManifest.xml for this to work.
NOTE2: public NetworkInfo getNetworkInfo (int networkType) is now deprecated:
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.
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
}
}
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.
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
}
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.
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:
Kotlin:
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 {
val networkInfo = connMgr.activeNetworkInfo ?: return false
return networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_WIFI
}
Java:
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 {
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}
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)
{
boolean br = false;
ConnectivityManager cm = null;
NetworkInfo ni = null;
cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
ni = cm.getActiveNetworkInfo();
br = ((null != ni) && (ni.isConnected()) && (ni.getType() == ConnectivityManager.TYPE_WIFI));
return br;
}
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
instead of:
getIpAddress() == 0 that is only valid for IP V4 or
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:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Proposed code is:
class MyViewModel(application: Application) : AndroidViewModel(application) {
// Get application context
private val myAppContext: Context = getApplication<Application>().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)
}
}
Using WifiManager you can do:
WifiManager wifi = (WifiManager) getSystemService (Context.WIFI_SERVICE);
if (wifi.getConnectionInfo().getNetworkId() != -1) {/* connected */}
The method getNeworkId returns -1 only when it's not connected to a network;
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean is3g = manager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
boolean isWifi = manager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
Log.v("", is3g + " ConnectivityManager Test " + isWifi);
if (!is3g && !isWifi) {
Toast.makeText(
getApplicationContext(),
"Please make sure, your network connection is ON ",
Toast.LENGTH_LONG).show();
}
else {
// Put your function() to go further;
}
This works for Android devices before and after Q
fun isWifiConnected(context: Context):Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val capabilities = cm.getNetworkCapabilities(cm.activeNetwork)
capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)==true
} else {
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
activeNetwork?.typeName?.contains("wifi",ignoreCase = true)?:false
}
}
Try out this method.
public boolean isInternetConnected() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean ret = true;
if (conMgr != null) {
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i != null) {
if (!i.isConnected()) {
ret = false;
}
if (!i.isAvailable()) {
ret = false;
}
}
if (i == null)
ret = false;
} else
ret = false;
return ret;
}
This method will help to find internet connection available or not.
This works for me:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Mobile
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
// Wi-Fi
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
// And then use it like this:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Mobile is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Wifi is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(Wifi_Gprs.this,"No Wifi or Gprs Enabled :( ....",Toast.LENGTH_LONG).show();
}
And add this permission:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Similar to #Jason Knight answer, but in Kotlin way:
val connManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
if (mWifi.isConnected) {
// Do whatever
}
Here is what I use as a utility method in my apps:
public static boolean isDeviceOnWifi(final Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi != null && mWifi.isConnectedOrConnecting();
}
In new version Android
private void getWifiInfo(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = connManager.getAllNetworks();
if(networks == null || networks.length == 0)
return;
for( int i = 0; i < networks.length; i++) {
Network ntk = networks[i];
NetworkInfo ntkInfo = connManager.getNetworkInfo(ntk);
if (ntkInfo.getType() == ConnectivityManager.TYPE_WIFI && ntkInfo.isConnected() ) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null) {
// add some code here
}
}
}
}
and add premission too
This is an easier solution. See Stack Overflow
question Checking Wi-Fi enabled or not on Android.
P.S. Do not forget to add the code to the manifest.xml file to allow permission. As shown below.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
</uses-permission>
Try
wifiManager.getConnectionInfo().getIpAddress()
This returns 0 until the device has a usable connection (on my machine, a Samsung SM-T280, Android 5.1.1).
You can turn WIFI on if it's not activated as the following
1. check WIFI state as answered by #Jason Knight
2. if not activated, activate it
don't forget to add WIFI permission in the manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Your Java class should be like that
public class TestApp extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//check WIFI activation
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected() == false) {
showWIFIDisabledAlertToUser();
}
else {
Toast.makeText(this, "WIFI is Enabled in your devide", Toast.LENGTH_SHORT).show();
}
}
private void showWIFIDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("WIFI is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable WIFI",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
Settings.ACTION_WIFI_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
Add this for JAVA:
public boolean CheckWifiConnection() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
in Manifest file add the following permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Kind of old a question but this is what i use. requires min api level 21 also takes in consideration deprecated Networkinfo apis.
boolean isWifiConn = false;
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network network = connMgr.getActiveNetwork();
if (network == null) return false;
NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network);
if(capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
isWifiConn = true;
Toast.makeText(context,"Wifi connected Api >= "+Build.VERSION_CODES.M,Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context,"Wifi not connected Api >= "+Build.VERSION_CODES.M,Toast.LENGTH_LONG).show();
}
} else {
for (Network network : connMgr.getAllNetworks()) {
NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) {
isWifiConn = true;
Toast.makeText(context,"Wifi connected ",Toast.LENGTH_LONG).show();
break;
}else{
Toast.makeText(context,"Wifi not connected ",Toast.LENGTH_LONG).show();
}
}
}
return isWifiConn;
val wifi = context!!.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
if (wifi!!.isWifiEnabled)
//do action here
else
//do action here
This works with the latest versions of android:
fun getConnectionType(context: Context): ConnectivityType {
var result = NONE
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
val capabilities = cm.getNetworkCapabilities(cm.activeNetwork)
if (capabilities != null) {
when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
result = WIFI
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
result = MOBILE_DATA
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> {
result = VPN
}
}
}
}
} else {
if (cm != null) {
val activeNetwork = cm.activeNetworkInfo
if (activeNetwork != null) {
// connected to the internet
when (activeNetwork.type) {
ConnectivityManager.TYPE_WIFI -> {
result = WIFI
}
ConnectivityManager.TYPE_MOBILE -> {
result = MOBILE_DATA
}
ConnectivityManager.TYPE_VPN -> {
result = VPN
}
}
}
}
}
return result
}
enum class ConnectivityType {
NONE,
MOBILE_DATA,
WIFI,
VPN,
}
And in the manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Proper way to check if Wifi is connected in android

For my app, I need to make sure the user is connected to wifi before contact with the server. I have found two methods to do so, but I am not sure if one suffices.
First I am adding this:
WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext()
.getSystemService(WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
buildAlertNoWifi();
showProgressDialog(false, "");
return;
}
And then I am doing this:
ConnectivityManager cm = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
Toast.makeText(getContext(), "Make sure you connect to wifi.", Toast.LENGTH_LONG).show();
return;
}
} else {
Toast.makeText(getContext(), "Make sure you connect to wifi.", Toast.LENGTH_LONG).show();
return;
}
So I was wondering if wifiManager.isWifiEnabled() returns whether the device is connected to a wifi or just has wifi turned on. And if so, is it enough to use it alone?
I believe WifiManager.isWifiEnabled() only checks if device's wifi is turned on. Please use NetworkInfo.isConnected() or NetworkInfo.isConnectedOrConnecting() to check if it's connected to any network.
Best Practice
public boolean isWifiConnected() {
NetworkInfo net = getActiveNetworkInfo();
return (isConnected(net) && net.getType() == TYPE_WIFI);
}
private NetworkInfo getActiveNetworkInfo() {
ConnectivityManager connManager = (ConnectivityManager)
Application.getContext()
.getSystemService(Application.CONNECTIVITY_SERVICE);
return connManager.getActiveNetworkInfo();
}
I believe this should work,
public boolean isWifiConnected()
{
ConnectivityManager cm = (ConnectivityManager)this.mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
return (cm != null) && (cm.getActiveNetworkInfo() != null) &&
(cm.getActiveNetworkInfo().getType() == 1);
}

Get Wifi information in Android library project [duplicate]

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) {
return false;
}
However, the state is not what I would expect. Even though Wi-Fi is connected, I am getting OBTAINING_IPADDR as the state.
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
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
to your
AndroidManifest.xml for this to work.
NOTE2: public NetworkInfo getNetworkInfo (int networkType) is now deprecated:
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.
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
}
}
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.
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
}
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.
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:
Kotlin:
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 {
val networkInfo = connMgr.activeNetworkInfo ?: return false
return networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_WIFI
}
Java:
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 {
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}
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)
{
boolean br = false;
ConnectivityManager cm = null;
NetworkInfo ni = null;
cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
ni = cm.getActiveNetworkInfo();
br = ((null != ni) && (ni.isConnected()) && (ni.getType() == ConnectivityManager.TYPE_WIFI));
return br;
}
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
instead of:
getIpAddress() == 0 that is only valid for IP V4 or
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:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Proposed code is:
class MyViewModel(application: Application) : AndroidViewModel(application) {
// Get application context
private val myAppContext: Context = getApplication<Application>().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)
}
}
Using WifiManager you can do:
WifiManager wifi = (WifiManager) getSystemService (Context.WIFI_SERVICE);
if (wifi.getConnectionInfo().getNetworkId() != -1) {/* connected */}
The method getNeworkId returns -1 only when it's not connected to a network;
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean is3g = manager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
boolean isWifi = manager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
Log.v("", is3g + " ConnectivityManager Test " + isWifi);
if (!is3g && !isWifi) {
Toast.makeText(
getApplicationContext(),
"Please make sure, your network connection is ON ",
Toast.LENGTH_LONG).show();
}
else {
// Put your function() to go further;
}
This works for Android devices before and after Q
fun isWifiConnected(context: Context):Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val capabilities = cm.getNetworkCapabilities(cm.activeNetwork)
capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)==true
} else {
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
activeNetwork?.typeName?.contains("wifi",ignoreCase = true)?:false
}
}
Try out this method.
public boolean isInternetConnected() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean ret = true;
if (conMgr != null) {
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i != null) {
if (!i.isConnected()) {
ret = false;
}
if (!i.isAvailable()) {
ret = false;
}
}
if (i == null)
ret = false;
} else
ret = false;
return ret;
}
This method will help to find internet connection available or not.
This works for me:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Mobile
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
// Wi-Fi
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
// And then use it like this:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Mobile is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Wifi is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(Wifi_Gprs.this,"No Wifi or Gprs Enabled :( ....",Toast.LENGTH_LONG).show();
}
And add this permission:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Similar to #Jason Knight answer, but in Kotlin way:
val connManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
if (mWifi.isConnected) {
// Do whatever
}
Here is what I use as a utility method in my apps:
public static boolean isDeviceOnWifi(final Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi != null && mWifi.isConnectedOrConnecting();
}
In new version Android
private void getWifiInfo(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = connManager.getAllNetworks();
if(networks == null || networks.length == 0)
return;
for( int i = 0; i < networks.length; i++) {
Network ntk = networks[i];
NetworkInfo ntkInfo = connManager.getNetworkInfo(ntk);
if (ntkInfo.getType() == ConnectivityManager.TYPE_WIFI && ntkInfo.isConnected() ) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null) {
// add some code here
}
}
}
}
and add premission too
This is an easier solution. See Stack Overflow
question Checking Wi-Fi enabled or not on Android.
P.S. Do not forget to add the code to the manifest.xml file to allow permission. As shown below.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
</uses-permission>
Try
wifiManager.getConnectionInfo().getIpAddress()
This returns 0 until the device has a usable connection (on my machine, a Samsung SM-T280, Android 5.1.1).
You can turn WIFI on if it's not activated as the following
1. check WIFI state as answered by #Jason Knight
2. if not activated, activate it
don't forget to add WIFI permission in the manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Your Java class should be like that
public class TestApp extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//check WIFI activation
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected() == false) {
showWIFIDisabledAlertToUser();
}
else {
Toast.makeText(this, "WIFI is Enabled in your devide", Toast.LENGTH_SHORT).show();
}
}
private void showWIFIDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("WIFI is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable WIFI",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
Settings.ACTION_WIFI_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
Add this for JAVA:
public boolean CheckWifiConnection() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
in Manifest file add the following permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Kind of old a question but this is what i use. requires min api level 21 also takes in consideration deprecated Networkinfo apis.
boolean isWifiConn = false;
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network network = connMgr.getActiveNetwork();
if (network == null) return false;
NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network);
if(capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
isWifiConn = true;
Toast.makeText(context,"Wifi connected Api >= "+Build.VERSION_CODES.M,Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context,"Wifi not connected Api >= "+Build.VERSION_CODES.M,Toast.LENGTH_LONG).show();
}
} else {
for (Network network : connMgr.getAllNetworks()) {
NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) {
isWifiConn = true;
Toast.makeText(context,"Wifi connected ",Toast.LENGTH_LONG).show();
break;
}else{
Toast.makeText(context,"Wifi not connected ",Toast.LENGTH_LONG).show();
}
}
}
return isWifiConn;
val wifi = context!!.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
if (wifi!!.isWifiEnabled)
//do action here
else
//do action here
This works with the latest versions of android:
fun getConnectionType(context: Context): ConnectivityType {
var result = NONE
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
val capabilities = cm.getNetworkCapabilities(cm.activeNetwork)
if (capabilities != null) {
when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
result = WIFI
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
result = MOBILE_DATA
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> {
result = VPN
}
}
}
}
} else {
if (cm != null) {
val activeNetwork = cm.activeNetworkInfo
if (activeNetwork != null) {
// connected to the internet
when (activeNetwork.type) {
ConnectivityManager.TYPE_WIFI -> {
result = WIFI
}
ConnectivityManager.TYPE_MOBILE -> {
result = MOBILE_DATA
}
ConnectivityManager.TYPE_VPN -> {
result = VPN
}
}
}
}
}
return result
}
enum class ConnectivityType {
NONE,
MOBILE_DATA,
WIFI,
VPN,
}
And in the manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

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) {
return false;
}
However, the state is not what I would expect. Even though Wi-Fi is connected, I am getting OBTAINING_IPADDR as the state.
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
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
to your
AndroidManifest.xml for this to work.
NOTE2: public NetworkInfo getNetworkInfo (int networkType) is now deprecated:
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.
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
}
}
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.
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
}
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.
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:
Kotlin:
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 {
val networkInfo = connMgr.activeNetworkInfo ?: return false
return networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_WIFI
}
Java:
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 {
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}
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)
{
boolean br = false;
ConnectivityManager cm = null;
NetworkInfo ni = null;
cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
ni = cm.getActiveNetworkInfo();
br = ((null != ni) && (ni.isConnected()) && (ni.getType() == ConnectivityManager.TYPE_WIFI));
return br;
}
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
instead of:
getIpAddress() == 0 that is only valid for IP V4 or
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:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Proposed code is:
class MyViewModel(application: Application) : AndroidViewModel(application) {
// Get application context
private val myAppContext: Context = getApplication<Application>().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)
}
}
Using WifiManager you can do:
WifiManager wifi = (WifiManager) getSystemService (Context.WIFI_SERVICE);
if (wifi.getConnectionInfo().getNetworkId() != -1) {/* connected */}
The method getNeworkId returns -1 only when it's not connected to a network;
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean is3g = manager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
boolean isWifi = manager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
Log.v("", is3g + " ConnectivityManager Test " + isWifi);
if (!is3g && !isWifi) {
Toast.makeText(
getApplicationContext(),
"Please make sure, your network connection is ON ",
Toast.LENGTH_LONG).show();
}
else {
// Put your function() to go further;
}
This works for Android devices before and after Q
fun isWifiConnected(context: Context):Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val capabilities = cm.getNetworkCapabilities(cm.activeNetwork)
capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)==true
} else {
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
activeNetwork?.typeName?.contains("wifi",ignoreCase = true)?:false
}
}
Try out this method.
public boolean isInternetConnected() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean ret = true;
if (conMgr != null) {
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i != null) {
if (!i.isConnected()) {
ret = false;
}
if (!i.isAvailable()) {
ret = false;
}
}
if (i == null)
ret = false;
} else
ret = false;
return ret;
}
This method will help to find internet connection available or not.
This works for me:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Mobile
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
// Wi-Fi
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
// And then use it like this:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Mobile is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Wifi is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(Wifi_Gprs.this,"No Wifi or Gprs Enabled :( ....",Toast.LENGTH_LONG).show();
}
And add this permission:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Similar to #Jason Knight answer, but in Kotlin way:
val connManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
if (mWifi.isConnected) {
// Do whatever
}
Here is what I use as a utility method in my apps:
public static boolean isDeviceOnWifi(final Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi != null && mWifi.isConnectedOrConnecting();
}
In new version Android
private void getWifiInfo(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = connManager.getAllNetworks();
if(networks == null || networks.length == 0)
return;
for( int i = 0; i < networks.length; i++) {
Network ntk = networks[i];
NetworkInfo ntkInfo = connManager.getNetworkInfo(ntk);
if (ntkInfo.getType() == ConnectivityManager.TYPE_WIFI && ntkInfo.isConnected() ) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null) {
// add some code here
}
}
}
}
and add premission too
This is an easier solution. See Stack Overflow
question Checking Wi-Fi enabled or not on Android.
P.S. Do not forget to add the code to the manifest.xml file to allow permission. As shown below.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
</uses-permission>
Try
wifiManager.getConnectionInfo().getIpAddress()
This returns 0 until the device has a usable connection (on my machine, a Samsung SM-T280, Android 5.1.1).
You can turn WIFI on if it's not activated as the following
1. check WIFI state as answered by #Jason Knight
2. if not activated, activate it
don't forget to add WIFI permission in the manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Your Java class should be like that
public class TestApp extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//check WIFI activation
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected() == false) {
showWIFIDisabledAlertToUser();
}
else {
Toast.makeText(this, "WIFI is Enabled in your devide", Toast.LENGTH_SHORT).show();
}
}
private void showWIFIDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("WIFI is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable WIFI",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
Settings.ACTION_WIFI_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
Add this for JAVA:
public boolean CheckWifiConnection() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
in Manifest file add the following permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Kind of old a question but this is what i use. requires min api level 21 also takes in consideration deprecated Networkinfo apis.
boolean isWifiConn = false;
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network network = connMgr.getActiveNetwork();
if (network == null) return false;
NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network);
if(capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
isWifiConn = true;
Toast.makeText(context,"Wifi connected Api >= "+Build.VERSION_CODES.M,Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context,"Wifi not connected Api >= "+Build.VERSION_CODES.M,Toast.LENGTH_LONG).show();
}
} else {
for (Network network : connMgr.getAllNetworks()) {
NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) {
isWifiConn = true;
Toast.makeText(context,"Wifi connected ",Toast.LENGTH_LONG).show();
break;
}else{
Toast.makeText(context,"Wifi not connected ",Toast.LENGTH_LONG).show();
}
}
}
return isWifiConn;
val wifi = context!!.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
if (wifi!!.isWifiEnabled)
//do action here
else
//do action here
This works with the latest versions of android:
fun getConnectionType(context: Context): ConnectivityType {
var result = NONE
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
val capabilities = cm.getNetworkCapabilities(cm.activeNetwork)
if (capabilities != null) {
when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
result = WIFI
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
result = MOBILE_DATA
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> {
result = VPN
}
}
}
}
} else {
if (cm != null) {
val activeNetwork = cm.activeNetworkInfo
if (activeNetwork != null) {
// connected to the internet
when (activeNetwork.type) {
ConnectivityManager.TYPE_WIFI -> {
result = WIFI
}
ConnectivityManager.TYPE_MOBILE -> {
result = MOBILE_DATA
}
ConnectivityManager.TYPE_VPN -> {
result = VPN
}
}
}
}
}
return result
}
enum class ConnectivityType {
NONE,
MOBILE_DATA,
WIFI,
VPN,
}
And in the manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Categories

Resources