Usually you do something like this:
@Override
public void onResume(){
super.onResume();
if ( isOnline ){
}else{
new AlertDialog.Builder(YourActivity.this)
.setTitle("Connection failed")
.setMessage("This application requires network access. Please, enable " +
"mobile network or Wi-Fi.")
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
YourActivity.this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
YourActivity.this.finish();
}
})
.show();
}
}
The idea is to ask the user to go over and set up a network connection. Then, if the user wants to configure it, you name the intent Settings.ACTION_WIRELESS_SETTINGS.
Also pay attention to the variable isOnline, which is a boolean that reports whether there is a network connection or not. To set this variable, you can use an external simple class as follows:
public class CheckConnectivity {
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if( cm == null )
return false;
NetworkInfo info = cm.getActiveNetworkInfo();
if( info == null )
return false;
return info.isConnectedOrConnecting();
}
}
In addition, you will need to add this permission to your AndroidManifest.xmlfile:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
source
share