In my application data comes from internet and I am trying to create a function that checks if a internet connection is available or not and if it isn't, it gives an alert messege that no internet connection available. i am using following code. but its not working.
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
if (isOnline())
{
// my code
}
else
{
Hotgames4meActivity1.this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
try {
AlertDialog alertDialog = new AlertDialog.Builder(Hotgames4meActivity1.this).create();
alertDialog.setTitle("Info");
alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
//alertDialog.setIcon(R.drawable.alerticon);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
}
catch(Exception e)
{
//Log.d(Constants.TAG, "Show Dialog: "+e.getMessage());
}
}
}
In android, we can determine the internet connection status easily by using getActiveNetworkInfo() method of ConnectivityManager object. Following is the code snippet of using the ConnectivityManager class to know whether the internet connection is available or not.
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
Toast.makeText(context, "No Internet connection!", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
And you must add premission for accessing network state and Internet:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With