Skip to content

Instantly share code, notes, and snippets.

@akexorcist
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akexorcist/3940108ebeb3565d0bbf to your computer and use it in GitHub Desktop.
Save akexorcist/3940108ebeb3565d0bbf to your computer and use it in GitHub Desktop.
ตรวจสอบว่าสามารถเชื่อมต่ออินเตอร์เน็ตได้หรือไม่ โดยใช้วิธี Ping ไปที่เซิฟเวอร์ของ Google
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL pingUrl = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection)pingUrl.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
// ผู้ใช้ต่อเนตและใช้งานได้
}
} catch (MalformedURLException e) {
e.printStackTrace();
// เน็ตไม่สามารถใช้งานได้
} catch (IOException e) {
e.printStackTrace();
// เน็ตไม่สามารถใช้งานได้
} catch (IllegalArgumentException e) {
e.printStackTrace();
// เน็ตไม่สามารถใช้งานได้
} catch (Exception e) {
e.printStackTrace();
// เน็ตไม่สามารถใช้งานได้
}
}
<uses-permission android:name="android.permission.INTERNET" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment