How to Check Internet Connection in Android with No Internet Connection Dialog?
Hello geeks, today we are going to learn that how we can add the functionality of Internet Alert to our application. You have definitely seen in almost all applications that when data is turned off or application is not able to get Internet then it pops up a message of “No Internet Connection” and then again it is connected to data is displays message as “Back Online’ or “Internet in connected”, we are going to implement the same in our application.
Goals/purposes of Internet Alert:
- To inform the user that he/she is not connected to the network.
- To stop all internet-related activities or services in the application.
What we are going to build in this article?
Here, we will be creating a button. Whenever the user will press the button message of Internet Connectivity will be displayed. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article.
Step by Step Implementation
Step 1: Creating a new project
- Open a new project.
- We will be working on Empty Activity with language as Java. Leave all other options unchanged.
- You can change the name of the project at your convenience.
- There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?
Step 2: Navigate to app > manifests > AndroidManifest.xml file and paste the following piece of code to add internet permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/>
Step 3: Working with activity_main.xml file
We are using a button in the activity_main.xml file to perform the action. Use the following code in the activity_main.xml file.
After implementing the above code, the design of the activity_main.xml file will look like this.
Step 4: Working with java files
Create a new java class named as ConnectionReceiver using the following method
Use the below code in the ConnectionReceiver.java file.
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Congratulations! we have successfully made the application to check Internet Connection and alert it to the user. Here is the final output of our application.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.