to check internet connectivity you can use the following.
Add the following permissions in manifest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Use a handler
Handler mHandler = new Handler();
boolean isRunning = true;
Then, use this thread from your onCreate() method :
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
try {
Thread.sleep(5000);
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
// Write your code here to update the UI.
displayData();
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
Then, declare this method which called by your handler at every 5 seconds :
private void displayData() {
ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf=cn.getActiveNetworkInfo();
if(nf != null && nf.isConnected()==true )
{
Toast.makeText(this, "Network Available", Toast.LENGTH_SHORT).show();
myTextView.setText("Network Available");
}
else
{
Toast.makeText(this, "Network Not Available", Toast.LENGTH_SHORT).show();
myTextView.setText("Network Not Available");
}
}
To stop thread call this :
isRunning = false;
Alterntively you ca use the below. But it does not check connectivty every 5 seonds
public class CheckNetwork {
private static final String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null)
{
Log.d(TAG,"no internet connection");
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG," internet connection available...");
return true;
}
else
{
Log.d(TAG," internet connection");
return true;
}
}
}
}
In your activity in onCreate()
if(CheckNetwork.isInternetAvailable(MainActivtiy.this)) //if connection available
{
}
http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
You can use a BroadCast Reciever. When connectivity is lost the system broadcasts. But i suggest not to use broadcast reciever.