Usually, you would do something like this:
@Override
public void onResume(){
super.onResume();
// first, check connectivity
if ( isOnline ){
// do things if it there's network connection
}else{
// as it seems there's no Internet connection
// ask the user to activate it
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) {
// THIS IS WHAT YOU ARE DOING, Jul
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 ask the user to go and configure a network connection. Then, if the user does want to configure it, you will call the Settings.ACTION_WIRELESS_SETTINGS
intent.
Also, notice the isOnline
variable, which is a boolean that tells whether there's a network connection or not. In order to set that variable you can use an external simple class like this:
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();
}
}
Also, you will have to add this permission to your AndroidManifest.xml
file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />