- How to check internet connection in android?
- How to Check Internet Connection in Android Programmatically?
- How to Check the Internet Availability in Android?
- Bonus: How to Check if the device is Connected to Wifi in Android?
- How to check internet connection in android using Broadcast Receiver
- How to Check Internet Connection in android using Broadcast Receiver
- Step 1: Create a new Project in android studio
- Step 2: add Network state permission on AndroidManifest.xml
- Step 3: Create a customDialog xml layout
- Step 4: Create a new java class, NetworkUtil
- Step 5 : Create a broadcast receiver class
- Step 6 : update broadcast receiver in androidmanifest.xml
- Step 7 : Call Broadcast receive from MainActivity.java
How to check internet connection in android?
This example demonstrate about how to check the state of internet connection through broadcast Receiver.
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 − To find the internet status we have to add network state permission to AndroidManifest.xml file as shown below.
Step 3 − Following is the content of the modified main activity file MainActivity.java. This file can include each of the fundamental life cycle methods. We have created a text view, when use click on text view it going to call broadcastIntent() method to broadcast a CONNECTIVITY_ACTION intent.
import android.content.BroadcastReceiver; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity < private BroadcastReceiver MyReceiver = null; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MyReceiver = new MyReceiver(); TextView click=findViewById(R.id.click); click.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < broadcastIntent(); >>); > public void broadcastIntent() < registerReceiver(MyReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); >@Override protected void onPause() < super.onPause(); unregisterReceiver(MyReceiver); >>
Step 4 − Create a NetworkUtil class to find the net work status as show below.
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; class NetworkUtil < public static String getConnectivityStatusString(Context context) < String status = null; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null) < if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) < status = "Wifi enabled"; return status; >else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) < status = "Mobile data enabled"; return status; >> else < status = "No internet is available"; return status; >return status; > >
Step 5 −Create a broadcast receiver class and named as MyReceiver.java .This broadcast receiver going to update the ui from NetworkUtil class.
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyReceiver extends BroadcastReceiver < @Override public void onReceive(Context context, Intent intent) < String status = NetworkUtil.getConnectivityStatusString(context); if(status.isEmpty()) < status="No Internet Connection"; >Toast.makeText(context, status, Toast.LENGTH_LONG).show(); > >
Step 6 −Update your broadcast receiver in manifest file as shown below.
Step 7 −Following will be the content of res/layout/activity_main.xml file to include a textview to broadcast connectivity state intent.
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.
The above screen we have selected wifi connection and the output should be like this −
The above screen we have selected wifi connection and the output should be like this −
Click here to download the project code
How to Check Internet Connection in Android Programmatically?
Today, we will learn how to check the internet connection in Android. We will also see how to test if the connected network has access to the internet.
For this article, create a method called isDeviceOnline() in your MainActivity and call it from the onCreate() method. If the user is online, it returns true ; otherwise, false . It also takes the Context parameter.
import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.net.NetworkInfo import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import java.net.URL import javax.net.ssl.HttpsURLConnection import kotlin.concurrent.thread class MainActivity : AppCompatActivity() < private val tagLog = javaClass.simpleName as String override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val deviceOnline = isDeviceOnline(this.applicationContext) >private fun isDeviceOnline(context: Context): Boolean < >>
Add the following permissions in the Manifest file:
In Android, we can get the state of the network by using the ConnectivityManager API. We can get its object from the getSystemService() method.
val connManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
To check if the device is online, call the getNetworkCapabilities() method. It looks like this:
public NetworkCapabilities getNetworkCapabilities (Network network)
It takes the Network object. We can get it from the getActiveNetwork() method of ConnectivityManager class. It is available from API level 23. So, check the SDK version. We will look at the devices below API 23 in a moment.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < val networkCapabilities = connManager.getNetworkCapabilities(connManager.activeNetwork) >else
The method returns null when the device is offline.
if (networkCapabilities == null) < Log.d(tagLog, "Device Offline") return false >else
For the devices below Marshmallow, we should call getActiveNetworkInfo() method.
public NetworkInfo getActiveNetworkInfo ()
It returns the NetworkInfo object. It provides isConnectedOrConnecting() and isAvailable() functions. If both return true , the user is online.
val activeNetwork = connManager.activeNetworkInfo if (activeNetwork?.isConnectedOrConnecting == true && activeNetwork.isAvailable) < Log.d(tagLog, "Device Online") return true >else
Our final isDeviceOnline() looks like this:
private fun isDeviceOnline(context: Context): Boolean < val connManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < val networkCapabilities = connManager.getNetworkCapabilities(connManager.activeNetwork) if (networkCapabilities == null) < Log.d(tagLog, "Device Offline") return false >else < Log.d(tagLog, "Device Online") return true >> else < // below Marshmallow val activeNetwork = connManager.activeNetworkInfo if (activeNetwork?.isConnectedOrConnecting == true && activeNetwork.isAvailable) < Log.d(tagLog, "Device Online") return true >else < Log.d(tagLog, "Device Offline") return false >> >
How to Check the Internet Availability in Android?
There are some cases where users are connected to a network, but the network may not have access to the internet. For example:
- User enabled mobile data, but he or she has no data balance.
- The device is on a roaming network, and data roaming has been disabled.
- Some wifi networks ask for sign-in information. In this case, users cannot access the internet until the credentials are provided.
So, we should check if the network has access to the internet. NetworkCapabilities API provides hasCapability() method.
public boolean hasCapability (int capability)
It takes a capability (an integer constant). To determine if the network has internet availability, we will use the following 3 constants:
NET_CAPABILITY_INTERNET: It shows that the network should be able to reach the internet.
NET_CAPABILITY_VALIDATED: It indicates that internet connectivity was successfully detected.
NET_CAPABILITY_NOT_SUSPENDED: It indicates that the network can transfer data.
if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED) ) < Log.d(tagLog, "Connected to Internet") return true >else
For the devices below Marshmallow (API 23), we can use NetworkInfo.State API.
activeNetwork = connManager.activeNetworkInfo when (activeNetwork?.state) < NetworkInfo.State.CONNECTED -> < Log.d(tagLog, " CONNECTED ") >NetworkInfo.State.CONNECTING -> < Log.d(tagLog, " CONNECTING ") >else -> < Log.d(tagLog, "NO CONNECTION") >>
Our isDeviceOnline() method:
private fun isDeviceOnline(context: Context): Boolean < val connManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < val networkCapabilities = connManager.getNetworkCapabilities(connManager.activeNetwork) if (networkCapabilities == null) < Log.d(tagLog, "Device Offline") return false >else < Log.d(tagLog, "Device Online") if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED) ) < Log.d(tagLog, "Connected to Internet") return true >else < Log.d(tagLog, "Not connected to Internet") return false >> > else < // below Marshmallow val activeNetwork = connManager.activeNetworkInfo if (activeNetwork?.isConnectedOrConnecting == true && activeNetwork.isAvailable) < Log.d(tagLog, "Device Online") when (activeNetwork.state) < NetworkInfo.State.CONNECTED -> < Log.d(tagLog, " CONNECTED ") return true >NetworkInfo.State.CONNECTING -> < Log.d(tagLog, " CONNECTING ") return true >else -> < Log.d(tagLog, "NO Connection") return false >> > else < Log.d(tagLog, "Device Offline") return false >> >
But the above code is not working under some conditions. This is how I tested:
I called the above method in an infinite loop from the onCreate() :
override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) thread < while (true) < val deviceOnline = isDeviceOnline(this.applicationContext) Log.d(tagLog, "deviceOnline $deviceOnline") Thread.sleep(1000) >> >
I turned on cellular data and hotspot on my mobile and connected my laptop to the hotspot. I run the above code on a virtual device. The Logcat was showing that the device is online. While the thread is running, I turned off the mobile data. But the Logcat was still displaying the online message.
The above code shows offline when the user connects to a network that has no internet availability. If the user loses the internet after connecting to the network, the code still returns true. Also, on Pixel XL API 22, even if the user connects to a network that cannot access internet, the method still returns true. To fix these problems:
- Remove the NetworkInfo.State conditions because they are not working in API 22
- Send Https request to a server
fun isInternetAvailable(): Boolean < val urlConnection = URL("https://clients3.google.com/generate_204").openConnection() as HttpsURLConnection try < urlConnection.setRequestProperty("User-Agent", "Android") urlConnection.setRequestProperty("Connection", "close") urlConnection.connectTimeout = 1000 urlConnection.connect() return urlConnection.responseCode == 204 >catch (e: Exception) < return false >>
The final code that gives 100% accurate results:
import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.net.NetworkInfo import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import java.net.URL import javax.net.ssl.HttpsURLConnection import kotlin.concurrent.thread class MainActivity : AppCompatActivity() < private val tagLog = javaClass.simpleName as String override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) thread < while (true) < val deviceOnline = isDeviceOnline(this.applicationContext) val internetAvailable = isInternetAvailable() Log.d(tagLog, "deviceOnline $deviceOnline") Log.d(tagLog, "internetAvailable $internetAvailable") Thread.sleep(1000) >> > private fun isDeviceOnline(context: Context): Boolean < val connManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < val networkCapabilities = connManager.getNetworkCapabilities(connManager.activeNetwork) if (networkCapabilities == null) < Log.d(tagLog, "Device Offline") return false >else < Log.d(tagLog, "Device Online") if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED) ) < Log.d(tagLog, "Connected to Internet") return true >else < Log.d(tagLog, "Not connected to Internet") return false >> > else < // below Marshmallow val activeNetwork = connManager.activeNetworkInfo return activeNetwork?.isConnectedOrConnecting == true && activeNetwork.isAvailable >> fun isInternetAvailable(): Boolean < val urlConnection = URL("https://clients3.google.com/generate_204").openConnection() as HttpsURLConnection try < urlConnection.setRequestProperty("User-Agent", "Android") urlConnection.setRequestProperty("Connection", "close") urlConnection.connectTimeout = 1000 urlConnection.connect() return urlConnection.responseCode == 204 >catch (e: Exception) < return false >> >
Bonus: How to Check if the device is Connected to Wifi in Android?
We can check if the device is connected to wifi or a cellular network by using the hasTransport() method of NetworkCapabilities class.
public boolean hasTransport (int transportType)
transportType for the cellular network is TRANSPORT_CELLULAR and wifi is TRANSPORT_WIFI.
For the devices running Marshmallow and lower, the getType() method returns the type of the network.
Here is the full code:
import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import kotlin.concurrent.thread class MainActivity : AppCompatActivity() < private val tagLog = javaClass.simpleName as String override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) thread < while (true) < typeOfNetwork(this.applicationContext) Thread.sleep(1000) >> > private fun typeOfNetwork(context: Context) < val connManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < val networkCapabilities = connManager.getNetworkCapabilities(connManager.activeNetwork) if (networkCapabilities == null) < Log.d(tagLog, "Device Offline") >else < Log.d(tagLog, "Device Online") if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) < Log.d(tagLog, "Wifi") >else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) < Log.d(tagLog, "Cellular") >else < Log.d(tagLog, "Unknown network") >> > else < // below Marshmallow val activeNetwork = connManager.activeNetworkInfo if (activeNetwork?.isConnectedOrConnecting == true && activeNetwork.isAvailable) < Log.d(tagLog, "Device Online") when (activeNetwork.type) < ConnectivityManager.TYPE_WIFI -> < Log.d(tagLog, "Wifi") >ConnectivityManager.TYPE_MOBILE -> < Log.d(tagLog, "Cellular") >else -> < Log.d(tagLog, "Unknown network") >> > else < Log.d(tagLog, "Device Offline") >> > >
Note: NetworkInfo has been deprecated in API 29. We are using it in marshmallow (API 23), so we don’t get any problems.
This is how you check the internet connection in Android programmatically. I hope you have learned something new. If you have any doubts, comment below.
How to check internet connection in android using Broadcast Receiver
Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will create a demo on how to check the state of internet connection using android broadcast receiver.
How to Check Internet Connection in android using Broadcast Receiver
Step 1: Create a new Project in android studio
OffCourse you need to Create a new Project,
Go to File > New Project and then fill all the details like app name, android package name, etc and hit the finish button to create new android project.
Step 2: add Network state permission on AndroidManifest.xml
Now, Open AndroidManifest.xml file and ACCESS_NETWORK_STATE permission
Step 3: Create a customDialog xml layout
This customDialog will be shown to user when user android device is not connect to internet.
Step 4: Create a new java class, NetworkUtil
Then, on the left Project section
app > java > your package name ( right click ) > New > Java Class
Create a NetworkUtil class to find the network status as show below.
NetworkUtil.java
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; class NetworkUtil < public static String getConnectivityStatusString(Context context) < String status = null; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null) < if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) < status = "Wifi enabled"; return status; >else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) < status = "Mobile data enabled"; return status; >> else < status = "No internet is available"; return status; >return status; > >
Step 5 : Create a broadcast receiver class
This broadcart receiver in android will keep track of when internet is connected or disconnected by using which we can easily update UI updates to the users.
app > java > your package name ( right click ) > New > Java Class
MyReceiver.java
import android.app.Activity; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MyReceiver extends BroadcastReceiver < Dialog dialog; TextView nettext; @Override public void onReceive(final Context context, final Intent intent) < String status = NetworkUtil.getConnectivityStatusString(context); dialog = new Dialog(context,android.R.style.Theme_NoTitleBar_Fullscreen); dialog.setContentView(R.layout.customdialog); Button restartapp = (Button)dialog.findViewById(R.id.restartapp); nettext =(TextView)dialog.findViewById(R.id.nettext); restartapp.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < ((Activity) context).finish(); Log.d("clickedbutton","yes"); Intent i = new Intent(context, MainActivity.class); context.startActivity(i); >>); Log.d("network",status); if(status.isEmpty()||status.equals("No internet is available")||status.equals("No Internet Connection")) < status="No Internet Connection"; dialog.show(); >Toast.makeText(context, status, Toast.LENGTH_LONG).show(); > >
Step 6 : update broadcast receiver in androidmanifest.xml
Then you need to update the broadcast receiver, so add the tag in manifest file.
Under tag just all the below tag code.
Step 7 : Call Broadcast receive from MainActivity.java
Then you need to make a call to broadcast receiver so that broadcast receiver get activited from your android app.
This broadcast reciever will keep track of CONNECTIVITY_ACTION like internet connectivity on/off.
MainActivity.java
import android.content.BroadcastReceiver; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity < private BroadcastReceiver MyReceiver = null; @Override protected void onCreate(@Nullable Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MyReceiver = new MyReceiver(); broadcastIntent(); >public void broadcastIntent() < registerReceiver(MyReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); >@Override protected void onPause() < super.onPause(); unregisterReceiver(MyReceiver); >>
Finally your android app is ready to check internet connection is on or off.