检查互联网连接是否正常

时间:2014-02-23 09:30:13

标签: java android performance

我正在使用以下方法检查互联网连接但它正在崩溃..

public static boolean CheckInternetConnection() {

    ConnectivityManager connec = (ConnectivityManager) PropertyApplication
            .getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    android.net.NetworkInfo wifi = connec
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    android.net.NetworkInfo mobile = connec
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (wifi != null && wifi.isConnected()) {
        return true;
    } else if (mobile != null && mobile.isConnected()) {
        return true;
    }

    return false;
}

此外,我在清单文件中添加了使用权限。这是我的清单

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

这是我的logcat

02-23 09:43:37.549: D/dalvikvm(1896): GC_FOR_ALLOC freed 36K, 8% free 2867K/3108K, paused 7ms, total 8ms
02-23 09:43:37.573: I/dalvikvm-heap(1896): Grow heap (frag case) to 3.909MB for 960012-byte allocation
02-23 09:43:37.673: D/dalvikvm(1896): GC_FOR_ALLOC freed 2K, 7% free 3802K/4048K, paused 49ms, total 49ms
02-23 09:43:37.729: D/main(1896): inside main
02-23 09:43:37.837: D/libEGL(1896): loaded /system/lib/egl/libEGL_genymotion.so
02-23 09:43:37.849: D/(1896): HostConnection::get() New Host Connection established 0xb93084a8, tid 1896
02-23 09:43:37.877: D/libEGL(1896): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
02-23 09:43:37.901: D/libEGL(1896): loaded /system/lib/egl/libGLESv2_genymotion.so
02-23 09:43:37.997: W/EGL_genymotion(1896): eglSurfaceAttrib not implemented
02-23 09:43:37.997: E/OpenGLRenderer(1896): Getting MAX_TEXTURE_SIZE from GradienCache
02-23 09:43:38.017: E/OpenGLRenderer(1896): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
02-23 09:43:38.017: D/OpenGLRenderer(1896): Enabling debug mode 0
02-23 09:43:39.745: D/main(1896): inside finally
02-23 09:43:40.045: D/dalvikvm(1896): GC_FOR_ALLOC freed 248K, 11% free 3750K/4200K, paused 8ms, total 8ms
02-23 09:43:40.069: I/dalvikvm-heap(1896): Grow heap (frag case) to 4.931MB for 1127532-byte allocation
02-23 09:43:40.097: D/dalvikvm(1896): GC_FOR_ALLOC freed 1K, 9% free 4850K/5304K, paused 23ms, total 23ms
02-23 09:43:40.257: W/EGL_genymotion(1896): eglSurfaceAttrib not implemented
02-23 09:43:42.513: W/EGL_genymotion(1896): eglSurfaceAttrib not implemented
02-23 09:43:49.373: D/dalvikvm(1896): GC_FOR_ALLOC freed 243K, 8% free 5201K/5644K, paused 54ms, total 65ms
02-23 09:43:49.577: I/dalvikvm-heap(1896): Grow heap (frag case) to 6.237MB for 1011060-byte allocation
02-23 09:43:49.653: D/dalvikvm(1896): GC_FOR_ALLOC freed 987K, 22% free 5200K/6632K, paused 71ms, total 71ms
02-23 09:43:50.077: D/dalvikvm(1896): GC_FOR_ALLOC freed 11K, 22% free 5189K/6632K, paused 74ms, total 77ms
02-23 09:43:50.709: I/dalvikvm-heap(1896): Grow heap (frag case) to 9.118MB for 4044204-byte allocation
02-23 09:43:50.789: D/dalvikvm(1896): GC_FOR_ALLOC freed <1K, 14% free 9138K/10584K, paused 78ms, total 78ms
02-23 09:43:51.089: D/main(1896): inside prop home onCreate
02-23 09:43:51.129: I/Choreographer(1896): Skipped 148 frames!  The application may be doing too much work on its main thread.
02-23 09:43:51.285: W/EGL_genymotion(1896): eglSurfaceAttrib not implemented
02-23 09:43:53.609: D/main(1896): inside prop home intent
02-23 09:43:53.989: D/main(1896): inside prop home starting intent
02-23 09:43:54.101: D/main(1896): inside prop list onCreate
02-23 09:43:54.101: D/main(1896): inside prop list try block
02-23 09:43:54.109: D/main(1896): inside prop list try blocktrue
02-23 09:43:54.117: W/System.err(1896): java.lang.NullPointerException
02-23 09:43:54.121: W/System.err(1896):     at com.propvis.utils.PropertyUtil.CheckInternetConnection(PropertyUtil.java:61)
02-23 09:43:54.137: W/System.err(1896):     at com.propvis.activity.PropertyListActivity.onCreate(PropertyListActivity.java:41)
02-23 09:43:54.149: W/System.err(1896):     at android.app.Activity.performCreate(Activity.java:5133)
02-23 09:43:54.149: W/System.err(1896):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-23 09:43:54.165: W/System.err(1896):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
02-23 09:43:54.165: W/System.err(1896):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
02-23 09:43:54.169: W/System.err(1896):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-23 09:43:54.185: W/System.err(1896):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
02-23 09:43:54.189: W/System.err(1896):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-23 09:43:54.201: W/System.err(1896):     at android.os.Looper.loop(Looper.java:137)
02-23 09:43:54.205: W/System.err(1896):     at android.app.ActivityThread.main(ActivityThread.java:5103)
02-23 09:43:54.217: W/System.err(1896):     at java.lang.reflect.Method.invokeNative(Native Method)
02-23 09:43:54.217: W/System.err(1896):     at java.lang.reflect.Method.invoke(Method.java:525)
02-23 09:43:54.241: W/System.err(1896):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-23 09:43:54.245: W/System.err(1896):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-23 09:43:54.253: W/System.err(1896):     at dalvik.system.NativeStart.main(Native Method)
02-23 09:43:54.421: W/EGL_genymotion(1896): eglSurfaceAttrib not implemented

3 个答案:

答案 0 :(得分:0)

这是我使用的代码,我希望它也适合你。

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}

答案 1 :(得分:0)

另一种方法就是对Google开放Socket。当我需要测试连接时,我在许多项目中使用以下代码,它确实有效。

Socket socket;
final String host = "www.google.com";
final int port = 80;
final int timeout = 30000;   // 30 seconds

try {
  socket = new Socket();
  socket.connect(new InetSocketAddress(host, port), timeout);
}
catch (UnknownHostException uhe) {
  Log.e("Sock", "I couldn't resolve the host you've provided!");
}
catch (SocketTimeoutException ste) {
  Log.e("Sock", "After a reasonable amount of time, I'm not able to connect, probably I don't have connectivity!");
}
catch (IOException ioe) {
  Log.e("Sock", "Hmmm... Sudden disconnection, probably you should retry!");
} 
但是,这可能很棘手。正好在UnknownHostException s,可能需要更长的时间才能超时,大约需要45秒才能超时 - 但另一方面,这通常发生在无法解析主机时,这更像是意味着您的互联网访问错误配置了DNS解析(这是不可能的),或者您的连接已关闭(更有可能)。

无论如何,如果你想对冲你的赌注,你可以通过两种方式来解决这个问题:

  • 请勿使用主机,而是使用IP地址。您可以在主机上多次使用ping获取多个Google的IP。例如:

    shut-up@i-kill-you ~/services $ ping www.google.com
    PING www.google.com (173.194.40.179) 56(84) bytes of data.
    
  • 另一种解决方法是启动WatchDog线程并在所需时间后完成连接尝试。显然,强制整理意味着没有成功,所以在你的情况下,谷歌会失败。

答案 2 :(得分:0)

以工作版本为您提供样本:

public static boolean checkInternetConnection(Context Context) {

    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;
}