This question already has an answer here:
- Detect if Android device has Internet connection 9 answers
I tried the below code to check whether my mobile is connected to a wireless network and it works well when I want to know if my mobile is connected to the network, but it fails to give information about the internet access ... something like "Pinging" any website. Actually I followed many links but still no answer, so I'll be so thankful if anybody can help.
Thanks in Advance.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast t = new Toast(getApplicationContext());
if (isInternetOn()) {
// INTERNET IS AVAILABLE, DO STUFF..
Toast.makeText(ConnectivityTestActivity.this,"Network is Available", Toast.LENGTH_LONG).show();
}
else {
// NO INTERNET AVAILABLE, DO STUFF..
Toast.makeText(ConnectivityTestActivity.this,"No Network Available", Toast.LENGTH_LONG).show();
}
}
public final boolean isInternetOn() {
ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
// MESSAGE TO SCREEN FOR TESTING (IF REQ)
//Toast.makeText(this, connectionType + ” connected”, Toast.LENGTH_SHORT).show();
return true;
} else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED ) {
return false;
}
return false;
}}
EDIT:
Follow below link it contains a great answer for Ping google server and get result
https://stackoverflow.com/a/16458623/1239911