连接管理器始终检测是否存在Internet连接

时间:2014-08-26 06:47:36

标签: android android-studio ubuntu-14.04

在我执行操作之前,我试图检查我的设备是否已连接到互联网。目前我正在使用Android虚拟设备,代码如下。奇怪的是,它总是报告是真的(这意味着有互联网连接),即使我希望它返回虚假。这会给我的应用程序带来问题。我尝试了许多其他解决方案,包括Android Developer Documentation上的示例,结果相同。我做错了什么?

注意我已将活动和Activity :: getApplicationContext都作为Context对象传递,但没有成功。

     public boolean isConnectedToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        Log.v(this.getClass().getName(), info[i].toString());
                        return true;
                    }

        }
        return false;

}

2 个答案:

答案 0 :(得分:1)

试试这个:

final Handler mHandler = new Handler();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                     Context context = getApplicationContext();
                                     ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
                                     NetworkInfo networkInfo = null;
                                         networkInfo = connMgr.getActiveNetworkInfo();
                                         if (networkInfo != null && networkInfo.isConnected())
                                         {
                                             //Perform operation what yyou want to perform when you got Internet connection

                                         } 
                                    }
                            });
                            Thread.sleep(10000);
                        } catch (Exception e) {
                        }
                    }
                }
            }).start();

希望这可以帮到你!

答案 1 :(得分:1)

代码没有问题。问题是我试图禁用主机(笔记本电脑)互联网而不是手机本身。只需通过设置(在AVD中)禁用移动数据和wifi连接,然后它就能正常工作