强制执行A​​sync任务中的关闭窗口

时间:2015-04-14 10:31:02

标签: java android android-fragments

强制关闭窗口,当连接丢失后执行异步任务时。 我已经厌倦了使用ConnectivityManager来检查互联网连接,因为当设备连接到wifi而没有互联网连接时,ConnectivityManager显示已连接。任何人都可以帮助我吗?

public boolean isConnected(){
        boolean status=false;
        ConnectivityManager cManager=(ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo[] allNetworkInfo = cManager.getAllNetworkInfo();
        for (int i = 0; i<allNetworkInfo.length; i++){
            if (allNetworkInfo[i].getState() == NetworkInfo.State.CONNECTED){
                status = true;
            }
        }
        return  status;
    }

4 个答案:

答案 0 :(得分:1)

你差不多完成但需要检查网络是否正在连接或连接。

public boolean isConnected(){
        boolean status=false;
        ConnectivityManager cManager=(ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo[] allNetworkInfo = cManager.getAllNetworkInfo();
        for (int i = 0; i<allNetworkInfo.length; i++){
            if (allNetworkInfo[i].isConnectedOrConnecting()){
                status = true;
            }
        }
        return  status;
    }

我希望它可以帮助你...

答案 1 :(得分:0)

您可以尝试使用此代码查看它是否有效:

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

答案 2 :(得分:0)

试试这个适用于我的代码。

public static boolean isConnectedWithInternet(Context context) {
            // return true;
            boolean _isNetAvailable = false;
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo wifiNetwork = cm
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (wifiNetwork != null) {
                _isNetAvailable = wifiNetwork.isConnectedOrConnecting();
            }

            NetworkInfo mobileNetwork = cm
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mobileNetwork != null) {
                _isNetAvailable = mobileNetwork.isConnectedOrConnecting();
            }

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if (activeNetwork != null) {
                _isNetAvailable = activeNetwork.isConnectedOrConnecting();
            }
            // CGlobalVariables._isInternetOn = _isNetAvailable;

            return _isNetAvailable;

        }

答案 3 :(得分:0)

当无法访问Internet时,通常会获得UnknownHostException

在开始请求之前,您应始终检查连接状态。但是为了在此过程中处理连接丢失,您始终可以捕获UnknownHostException