Android应用程序中的Internet连接 [英] Internet Connectivity in android applications

查看:76
本文介绍了Android应用程序中的Internet连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用互联网连接从webservice接收数据的应用程序。但有时没有互联网连接,我的应用程序被强行关闭。为了防止这种情况,我想检查设备是否连接到互联网。

I am having an application which uses internet connection for receiving data from webservice. But at times of no internet connection my app is forcibly closed.So to prevent this I want to check whether the device is connected to internet or not.

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}







我已尝试过谷歌上面最常见的代码,但问题是即使没有互联网连接,它也会返回该设备正在使用互联网。请帮我一些工作代码。




I have tried the above most common code from google, but problem with that is that even with no internet connection it returns that the device is having internet. Please help me with some working code.

推荐答案

您好Kartik,请参考以下代码检查互联网连接。



Hi Kartik, Please refer to below code for checking internet connection.

public boolean isConnectingToInternet(){
     ConnectivityManager connectivity = (ConnectivityManager) _context.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)
                   {
                       return true;
                   }

       }
       return false;
 }





如需检测android中的连接状态,请参阅此 [ LINK ]


这篇关于Android应用程序中的Internet连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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