检查网络连接的android [英] Check network connection android

查看:201
本文介绍了检查网络连接的android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序,这是我测试的模拟器,我用下面的code检查网络连接(WIFI):

In my application, which I test on emulator, I use the following code to check the network connection (WIFI):

    public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

此方法总是返回,即使我禁用我的电脑的无线连接... 这是造成仿真器或者是其他什么东西?

This method returns always true, even if I disable the wireless connection of my computer... Is this caused by the emulator or is it something else?

如果这不是正确的方式来检查网络连接,我该怎么办呢?

If this is not the right way to check network connection, how can I do that?

推荐答案

试试这个code

 public boolean isNetworkOnline() {
    boolean status=false;
    try{
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getNetworkInfo(0);
        if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
            status= true;
        }else {
            netInfo = cm.getNetworkInfo(1);
            if(netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED)
                status= true;
        }
    }catch(Exception e){
        e.printStackTrace();  
        return false;
    }
    return status;

    }  

这篇关于检查网络连接的android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆