android中的Internet连接检查失败

时间:2013-12-30 05:35:25

标签: android internet-connection

我正在处理需要与服务器通信的应用程序。因此,实现了对互联网连接的检查。

当我使用移动数据和wifi时,检查完全正常。

问题是我的设备已连接热点。我点击登录按钮并获得进度条,指出"连接到服务器"。现在,我关闭了热点。但是我的设备启用了wifi。

(它无​​法获得任何responseCode)。

我的应用程序进入无限状态。

有关如何克服此问题的任何建议。

4 个答案:

答案 0 :(得分:2)

你也可以这样:

在您的包中创建两个java文件:NetworkConnectivity.javaNetworkMonitorListener.java,如下所示:

<强> NetworkConnectivity.java

public class NetworkConnectivity {

    private static NetworkConnectivity sharedNetworkConnectivity = null;

    private Activity activity = null;

    private final Handler handler = new Handler();
    private Runnable runnable = null;

    private boolean stopRequested = false;
    private boolean monitorStarted = false;

    private static final int NETWORK_CONNECTION_YES = 1;
    private static final int NETWORK_CONNECTION_NO = -1;
    private static final int NETWORK_CONNECTION_UKNOWN = 0;

    private int connected = NETWORK_CONNECTION_UKNOWN;

    public static final int MONITOR_RATE_WHEN_CONNECTED_MS = 5000;
    public static final int MONITOR_RATE_WHEN_DISCONNECTED_MS = 1000;

    private final List<NetworkMonitorListener> networkMonitorListeners = new ArrayList<NetworkMonitorListener>();

    private NetworkConnectivity() {
    }

    public synchronized static NetworkConnectivity sharedNetworkConnectivity() {
        if (sharedNetworkConnectivity == null) {
            sharedNetworkConnectivity = new NetworkConnectivity();
        }

        return sharedNetworkConnectivity;
    }

    public void configure(Activity activity) {
        this.activity = activity;
    }

    public synchronized boolean startNetworkMonitor() {
        if (this.activity == null) {
            return false;
        }

        if (monitorStarted) {
            return true;
        }

        stopRequested = false;
        monitorStarted = true;

        (new Thread(new Runnable() {
            @Override
            public void run() {
                doCheckConnection();
            }
        })).start();

        return true;
    }

    public synchronized void stopNetworkMonitor() {
        stopRequested = true;
        monitorStarted = false;
    }

    public void addNetworkMonitorListener(NetworkMonitorListener l) {
        this.networkMonitorListeners.add(l);
        this.notifyNetworkMonitorListener(l);
    }

    public boolean removeNetworkMonitorListener(NetworkMonitorListener l) {
        return this.networkMonitorListeners.remove(l);
    }

    private void doCheckConnection() {

        if (stopRequested) {
            runnable = null;
            return;
        }

        final boolean connectedBool = this.isConnected();
        final int _connected = (connectedBool ? NETWORK_CONNECTION_YES
                : NETWORK_CONNECTION_NO);

        if (this.connected != _connected) {

            this.connected = _connected;

            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    notifyNetworkMonitorListeners();
                }
            });
        }

        runnable = new Runnable() {
            @Override
            public void run() {
                doCheckConnection();
            }
        };

        handler.postDelayed(runnable,
                (connectedBool ? MONITOR_RATE_WHEN_CONNECTED_MS
                        : MONITOR_RATE_WHEN_DISCONNECTED_MS));
    }

    public boolean isConnected() {
        try {
            ConnectivityManager cm = (ConnectivityManager) activity
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();

            if (netInfo != null && netInfo.isConnected()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    private void notifyNetworkMonitorListener(NetworkMonitorListener l) {
        try {
            if (this.connected == NETWORK_CONNECTION_YES) {
                l.connectionEstablished();
            } else if (this.connected == NETWORK_CONNECTION_NO) {
                l.connectionLost();
            } else {
                l.connectionCheckInProgress();
            }
        } catch (Exception e) {
        }
    }

    private void notifyNetworkMonitorListeners() {
        for (NetworkMonitorListener l : this.networkMonitorListeners) {
            this.notifyNetworkMonitorListener(l);
        }
    }

}

<强> NetworkMonitorListener.java

public interface NetworkMonitorListener {

    public void connectionEstablished();
    public void connectionLost();
    public void connectionCheckInProgress();
}

最后,在您的活动中使用此类,如下所示:例如:

        NetworkConnectivity.sharedNetworkConnectivity().configure(this);
        NetworkConnectivity.sharedNetworkConnectivity().startNetworkMonitor();
        NetworkConnectivity.sharedNetworkConnectivity()
                .addNetworkMonitorListener(new NetworkMonitorListener() {
                    @Override
                    public void connectionCheckInProgress() {
                        // Okay to make UI updates (check-in-progress is rare)
                    }

                    @Override
                    public void connectionEstablished() {
                        // Okay to make UI updates -- do something now that
                        // connection is avaialble

                    }

                    @Override
                    public void connectionLost() {
                        // Okay to make UI updates -- bummer, no connection

                    }
                });

通过这种方式,您可以实时检查互联网连接,并采取相应的行动。

答案 1 :(得分:1)

public class checkconnection {

    public static boolean checkInternetConnection(Context context) {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        try {
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();
            for (NetworkInfo ni : netInfo) {
                if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                    if (ni.isConnected())
                        haveConnectedWifi = true;
                if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                    if (ni.isConnected())
                        haveConnectedMobile = true;
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
        return haveConnectedWifi || haveConnectedMobile;
    }


}

在拨打登录信息之前,请在班级中使用以下checkInternetConnection()方法。 true可确保您拥有连接。

答案 2 :(得分:0)

尝试使用此代码进行互联网检查: -

public static boolean isConnected(Context context) {
    ConnectivityManager manager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = manager.getActiveNetworkInfo();
    if (info == null)
        return false;
    if ((info.getState() != State.CONNECTED))
        return false;
    return true;
}

答案 3 :(得分:0)

希望以下代码可以帮助您。

public static boolean checkNetworkStatus(Context cxt) {
    boolean isFound = false;

    ConnectivityManager conMgr = (ConnectivityManager) cxt
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conMgr.getActiveNetworkInfo() != null
            && conMgr.getActiveNetworkInfo().isAvailable()
            && conMgr.getActiveNetworkInfo().isConnected()) {
        isFound = true;
    } else {
        isFound = false;
    }
    return isFound;
}

还在清单文件中使用以下权限。

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