【问题标题】:How to detect WIFI is connected, but no internet (data limit is over / no signal)如何检测WIFI已连接,但没有互联网(数据限制超过/无信号)
【发布时间】:2018-09-09 08:57:24
【问题描述】:

我想检查''Wifi'是否连接,但是如何检测互联网是否可用?因为在我的“MainActivity.java”中,我通过以下代码检查互联网连接以及互联网的可用性。

public static boolean isConnectedToInternet(Context context) {

   ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    if (cm.getActiveNetworkInfo() != null
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        Log.d("INTERNET_CONNECTION", "Internet is working");

        return true;
    } else {
        Log.d("INTERNET_CONNECTION", "Internet is Not Available");
        return false;
    }

}

如果互联网可用(数据和信号正常),“进度条”可见并加载内容,加载过程已完成,“进度条”不可见。如果互联网不可用(无数据或无信号),则“进度条”不可见并显示错误。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

        if (isConnectedToInternet(context)== true)
        {
            progressLayout.setVisibility(View.VISIBLE);

            // load the content
        }
        else
        {
            progressLayout.setVisibility(View.GONE);

            Toast.makeText(this, "No Internet", Toast.LENGTH_LONG).show;
        }
}

如果互联网可用,代码工作正常,但在互联网不可用时始终显示“进度条”。 (无数据或无信号)

【问题讨论】:

  • 你可以尝试做一些网络请求,比如获取谷歌主页来测试连接。
  • 在mainThred中怎么做
  • 你不应该在主线程中这样做。

标签: android progress-bar android-wifi android-connectivitymanager


【解决方案1】:
 public static boolean isNetworkAvailable(Context activity) {
    ConnectivityManager connectivity = (ConnectivityManager) activity
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (NetworkInfo anInfo : info) {
                if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}

【讨论】:

  • 我做了更改,但什么也没做
  • 您是否授予权限 1 ) 2)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-02
  • 1970-01-01
  • 2015-12-14
  • 2018-03-19
相关资源
最近更新 更多