简体   繁体   English

检查Android中的互联网连接是否处于活动状态

[英]Check if Internet Connection Is Active In Android

i am trying to check for internet connection in my application. 我正在尝试检查我的应用程序中的Internet连接。 first, i am checking if wifi or mobile data is on, then i am checking if there is an active internet connection. 首先,我要检查wifi或移动数据是否打开,然后要检查是否有活动的互联网连接。 what i am currently doing: 我目前在做什么:

    public class ConnectivityReceiver extends BroadcastReceiver {

    String TAG="ConnectivityReceiver";

public static boolean hasInternetAccess() {
    try {
        HttpURLConnection urlc = (HttpURLConnection)
                (new URL("http://clients3.google.com/generate_204")
                        .openConnection());
        urlc.setRequestProperty("User-Agent", "Android");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1500);
        urlc.connect();
        return (urlc.getResponseCode() == 204 &&
                urlc.getContentLength() == 0);
    } catch (IOException e) {

    }

    return false;
}


@Override
public void onReceive(Context arg0, Intent intent) {
      String action = intent.getAction();


        boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);
         if(noConnectivity){
             try{

                 TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_nowifi);
             }
             catch(Exception e)
             {

             }
         }
         else
         {
             Boolean status = hasInternetAccess();
             if(status==true)
             {
                 try{
                     TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_wifi);
                 }
                 catch(Exception e)
                 {

                 }
             }
             else
             {
                 try{

                     TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_nowifi);
                 }
                 catch(Exception e)
                 {

                 }
             }


         }


}

but i am getting the following error: 但我收到以下错误:

java.lang.RuntimeException: Unable to start receiver connectionchecker.ConnectivityReceiver: android.os.NetworkOnMainThreadException
            at android.app.ActivityThread.handleReceiver(ActivityThread.java:2668)
            at android.app.ActivityThread.access$1800(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5653)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
            at java.net.InetAddress.getAllByName(InetAddress.java:214)
            at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
            at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
            at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
            at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:390)
            at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:343)
            at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
            at connectionchecker.NetworkUtil.hasInternetAccess(NetworkUtil.java:21)
            at connectionchecker.ConnectivityReceiver.onReceive(ConnectivityReceiver.java:46)
            at android.app.ActivityThread.handleReceiver(ActivityThread.java:2653)
            at android.app.ActivityThread.access$1800(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5653)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
            at dalvik.system.NativeStart.main(Native Method)

You are trying to connect to the network in UI thread which is not allowed. 您正在尝试使用不允许的UI线程连接到网络。 to check for active internet connection use following method. 检查活动的互联网连接,请使用以下方法。

public boolean isConnected() {
    ConnectivityManager manager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo info = manager.getActiveNetworkInfo();
    if (info != null && info.isConnected()) {
        return true;
    } else {
        return false;

    }
}

Once you receive the value, if it is true proceed with network operation. 收到该值后,如果为true,则继续进行网络操作。 Else display the user a proper error message. 否则向用户显示正确的错误消息。

Caused by: android.os.NetworkOnMainThreadException

您需要不在UIthread上执行网络操作。

Sounds like you might need to use the getActiveNetworkInfo() call. 听起来您可能需要使用getActiveNetworkInfo()调用。 There is a few posts on stackoverflow already that document it extensively so rather than repeat those have a look at these: 关于stackoverflow的一些帖子已经对其进行了广泛的记录,因此与其重复,不妨看一下这些内容:

Detect whether there is an Internet connection available on Android 检测Android上是否有Internet连接可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM