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

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

问题描述

在我的应用程序中,我在模拟器上测试,我使用以下代码检查网络连接(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;
}

此方法总是返回 true 这是由模拟器造成的还是其他的?

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?

推荐答案

所以每个活动都可以调用这个函数,和(2)使这个函数静态:

It's better to (1) pass in the context so that the every activity can invoke this functions, and (2) Make this function static:

 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天全站免登陆