How can I do so that when the application is opened, and has no Internet connection appear a dialog informing the connection and with a button "Ok " that when bombed closes the application
Asked
Active
Viewed 2,029 times
-3
-
4Possible duplicate of [Display an alert when internet connection not available in android application](https://stackoverflow.com/questions/10242351/display-an-alert-when-internet-connection-not-available-in-android-application) – Nikunj Paradva Apr 23 '18 at 03:54
4 Answers
0
Use a utility method in Utility class
Utility class:
public static boolean hasNetwork (){
return instance.checkIfHasNetwork();
}
public boolean checkIfHasNetwork(){
ConnectivityManager cm = (ConnectivityManager) getSystemService( Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
Usage:
if (!Utility.hasNetwork()){
// show dialog
}
Also add permission in Manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Abu Yousuf
- 5,729
- 3
- 31
- 50
0
You can use the below code to check whether network is available. For further details, you can refer the documentation.
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

Shuwn Yuan Tee
- 5,578
- 6
- 28
- 42
0
Add this permission to your Manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Add to your activity
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager //get ConnectiviyManager
val networkInfo = cm.activeNetworkInfo //get network info
if(!networkInfo.isConnected){ //check if network is connected
val builder = AlertDialog.Builder(this) //create dialog builder
builder.setMessage("Dialog message") //set dialog message
.setTitle("Dialog title"); //set dialog title
builder.setNeutralButton(R.string.ok, DialogInterface.OnClickListener { dialog, id ->
dialog.dismiss() //add Ok button, when clicked close the dialog
})
builder.create().show()//show dialog
}
This is Kotlin.

Leonardo Velozo
- 598
- 1
- 6
- 16
0
First, declare permissions in the android manifest file to access network state.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Next, get android Connectivity manager using getSystemService.
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
If you only check is active network connection use isConnected.
Create a separate method and call this in onCreate method after setContentView

Bhanu Prakash Pasupula
- 962
- 2
- 9
- 25