我如何检查我的android设备在Android中有互联网连接?

时间:2016-03-26 09:07:20

标签: android

说明:            我正在尝试连接我的具有互联网连接的设备。我在网络状态和互联网上都添加了一个权限。我正确检查我的设备是否与特定的网络连接。 WIFI。

如何检查此wifi连接是否共享互联网。

这是我的类,它有两种互联网连接检查和网络连接检查方法。

package comman;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import java.net.URL;
import java.io.IOException;
import java.net.HttpURLConnection;


public class ConnectionDetector {
    private Context _context;

    public ConnectionDetector(Context context) {
        this._context = context;
    }

    public boolean isConnectingToInternet() {
        if (networkConnectivity()) {
            try {
                HttpURLConnection urlc = (HttpURLConnection) (new URL(
                        "http://www.google.com").openConnection());
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(3000);
                urlc.setReadTimeout(4000);
                urlc.connect();
                // networkcode2 = urlc.getResponseCode();
                return (urlc.getResponseCode() == 200);
            } catch (IOException e) {
                return (false);
            }
        } else
            return false;
    }

    private boolean networkConnectivity() {
        ConnectivityManager cm = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }
}

这是我试图检查设备是否有互联网连接的代码?

ConnectionDetector cd=new ConnectionDetector(getContext());

        if (cd.isConnectingToInternet()) {
            new TabJson().execute();
        }
        else{
            dialog_popup();
        } 

这里是一个例外

FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.angelnx.cricvilla.cricvilla/com.angelnx.cricvilla.cricvilla.MainActivity}: android.os.NetworkOnMainThreadException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
        at android.app.ActivityThread.access$700(ActivityThread.java:143)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4950)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
        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 libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
        at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
        at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
        at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
        at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
        at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
        at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
        at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
        at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
        at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
        at comman.ConnectionDetector.isConnectingToInternet(ConnectionDetector.java:29)
        at com.angelnx.cricvilla.cricvilla.HomeFragment.onCreateView(HomeFragment.java:130)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
        at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330)
        at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:547)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1178)
        at android.app.Activity.performStart(Activity.java:5187)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2083)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135) 
        at android.app.ActivityThread.access$700(ActivityThread.java:143) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:137) 
        at android.app.ActivityThread.main(ActivityThread.java:4950) 
        at java.lang.reflect.Method.invokeNative(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:511) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771) 
        at dalvik.system.NativeStart.main(Native Method)

我该如何解决这个问题? 请帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

这是因为你在主线程上调用了httprequest。请改用AsyncTask

答案 1 :(得分:0)

由于您在主线程中执行网络操作,因此抛出此异常。在你的背景线程中做。即AsyncTask

class Task extends AsyncTask<String, void, boolean> {

private Exception exception;

protected boolean doInBackground(String... xyz) {
    if (networkConnectivity()) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL(
                    "http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(3000);
            urlc.setReadTimeout(4000);
            urlc.connect();
            // networkcode2 = urlc.getResponseCode();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            return (false);
        }
    } else
        return false;
}


  private boolean networkConnectivity() {
    ConnectivityManager cm = (ConnectivityManager) _context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}


}