I have modified my previous code - this code is running properly. The only problem is that after launching it, on the first click it always shows an output as:
"Internet is not available"
But on the second click it shows the correct output.
public class MainActivity extends Activity {
boolean pingCheck;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread t = new Thread(new Runnable() {
public void run() {
pingCheck = isURLReachable(getApplicationContext());
}
});
t.start();
if(pingCheck)
{
Toast.makeText(MainActivity.this,"Network is available",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this,"Network not available",Toast.LENGTH_LONG).show();
}
}
});
}
static public boolean isURLReachable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://google.com"); // Change to "http://google.com" for www test.
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout( 1000); // 10 s.
urlc.connect();
if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http connection is fine).
Log.wtf("Connection", "Success !");
return true;
} else {
return false;
}
} catch (MalformedURLException e1) {
return false;
} catch (IOException e) {
return false;
}
}
return false;
}
}