Hello guys this is nice code to check internet availability. If you are testing it on android emulator then
1. go to Window menu2. Show view
3. other
4. Emulator control
5. Set value for Data as home (means network available)
6. Test application(it shows internet available)
7. Not set value for Data as denied ( means network connection denied)
8. Test application ( It shows internet not available)
All the above steps is just for emulator. If you are testing it on device no need to fallow these steps.
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class NetworkStatus extends Activity {
Intent i;
//public WebView mWebView;
protected ProgressDialog dialog;
static boolean value = false;
int DELAY = 1000;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
LoadData();
}
public void LoadData()
{
dialog = ProgressDialog.show(this, null, "Please wait..", true);
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
public void run()
{
checkConnection();
}
}, DELAY);
}
public void checkConnection()
{
// TODO Auto-generated method stub
if(isOnline())
{
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Internet Available", 3000).show();
// INTERNET IS AVAILABLE, DO STUFF..
}
else
{
// NO INTERNET AVAILABLE, DO STUFF..
dialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Info");
builder.setMessage("Internet not available");
builder.setPositiveButton("Try again", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog2, int which)
{
// Do nothing but close the dialog
dialog2.dismiss();
LoadData();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog2, int which)
{
// Do nothing
dialog2.dismiss();
}
});
builder.create();
builder.show();
}
}
// To check internet connection
protected boolean isOnline()
{
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
return true;
}
else
{
return false;
}
}
}
No comments:
Post a Comment