Advertisement
retnet

java android detected internet

Jun 19th, 2020
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. boolean haveNetworkConnection(android.content.Context context) {
  2. boolean haveConnectedWifi = false;
  3. boolean haveConnectedMobile = false;
  4. ConnectivityManager cm = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
  5. assert cm != null;
  6. NetworkInfo[] netInfo = cm.getAllNetworkInfo();
  7. for (NetworkInfo ni : netInfo) {
  8. if (ni.getTypeName().equalsIgnoreCase("WIFI"))
  9. if (ni.isConnected())
  10. haveConnectedWifi = true;
  11. if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
  12. if (ni.isConnected())
  13. haveConnectedMobile = true;
  14. }
  15. return haveConnectedWifi || haveConnectedMobile;
  16. }
  17.  
  18. ## usage
  19. if(!haveNetworkConnection(getApplicationContext())) {
  20. Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_SHORT).show();
  21. }else{
  22. Toast.makeText(getApplicationContext(), "Internet available", Toast.LENGTH_SHORT).show();
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement