本文介绍了ConnectivityManager验证Internet连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我需要验证,如果我的设备当前连接到互联网或没有,所以我写了这个类,它使用了 ConnectivityManager 查询:

 公共布尔checkInternetConnection(){
ConnectivityManager厘米=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);    如果(cm.getActiveNetworkInfo()=空&放大器;!&放大器; cm.getActiveNetworkInfo()isAvailable()及&放大器; cm.getActiveNetworkInfo()isConnected()){
        返回true;    }其他{
        返回false;
    }
}

的伟大工程,因为现在的方法是在主包( com.App )的类,但我要如何改变code键使它在 com.App.Utility

中定义的类工作

谢谢!


解决方案

 包com.app.utility;  公共类公用事业{    公共静态最终布尔CheckInternetConnection(上下文的背景下){
      ConnectivityManager厘米=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);      如果(cm.getActiveNetworkInfo()=空&放大器;!&放大器; cm.getActiveNetworkInfo()isAvailable()及&放大器; cm.getActiveNetworkInfo()isConnected()){
        返回true;      }其他{
        返回false;
      }
    }
  }

Hi all I need to verify if my device is currently connected to internet or not and so I wrote this class that uses a ConnectivityManager to check:

public boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
        return true;

    } else {
        return false;
    }
}

works great, because right now the method is in a class in the main package (com.App), but how should I change the code to make it work in a class defined in com.App.Utility ?

Thanks!

解决方案
package com.app.utility;

  public class Utilities {

    public static final boolean CheckInternetConnection(Context context) {
      ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

      if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
        return true;

      } else {
        return false;
      }
    }
  }

这篇关于ConnectivityManager验证Internet连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 19:45