0

我正在尝试确定我的应用程序中是否有活动的互联网连接。我需要知道我是否可以无任何错误地访问网络,有时即使我没有互联网连接,我也会得到“真实”的响应,那是因为我仍然连接到 WiFi 但没有互联网连接。

同时,我的上网查功能是:

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

此功能仅检查我是否连接到某个 WiFi 或移动网络,而不实际检查我是否可以访问网络。

所以我添加了下一个功能:

public boolean isInternetAvailable() {
    try {
        InetAddress ipAddr = InetAddress.getByName("google.com");
        return !ipAddr.equals("");
    } catch (Exception e) {
        return false;
    }
}

我不知道为什么,但这个功能总是认为我的互联网连接正常,即使我的路由器没有连接(我在网络栏上有一个黄色的小三角形,表示已连接但没有互联网连接)。

如果连接是真/假,我每次调用此函数时都尝试打印,并且在连接时我得到真,拔下路由器后我得到假 5-10 秒,然后我得到再次为真......(不连接到其他 WiFi 网络)

我试图在 ADB 模拟器和实际设备上对此进行测试,但它们都崩溃了,因为即使我“离线”也试图访问网络。

寻求帮助!非常感谢你。

4

3 回答 3

0

而不是 isConnected() 方法

   return activeNetworkInfo != null && activeNetworkInfo.isConnected();

试试这个

return activeNetwork !=null && activeNetwork.isConnectedOrConnecting();

这是我通常使用的实用程序类:

public class NetworkHelper {

    //method that checks for network status
    public static boolean hasNetworkAccess(Context context){

        ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        try {
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork !=null && activeNetwork.isConnectedOrConnecting();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

}

确保您有权限

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

在你的活动中做一个

private boolean networkOk;

然后用它来看看你的连接是否正常

    networkOk = NetworkHelper.hasNetworkAccess(this);
    if (networkOk) {
        Intent intent = new Intent(MainActivity.this, Myservice.class);
        intent.setData(Uri.parse(jsonurl));
        startService(intent);
    }
于 2017-08-14T05:17:08.833 回答
0

这对我有用:

public boolean hasNetworkAccess() {
    if (hasActiveInternetConnection()) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.screens.company").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            System.out.println("NETWORK CHECK");
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            Log.e("NETWORK", "Error checking internet connection.");
        }
    } else {
        Log.d("NETWORK", "No network available!");
    }
    return false;
}

public boolean hasActiveInternetConnection() {
    ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
    try {
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        System.out.println("Debug: [Network] Status: " + (activeNetwork != null && activeNetwork.isConnectedOrConnecting()));
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    } catch (Exception e) {
        System.out.println("Debug: [Network] Status: NOT CONNECTED.");
        e.printStackTrace();
        return false;
    }
}
于 2017-08-15T20:06:07.373 回答
0

这实际上会检查互联网

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

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


public class NetStatus {

    private static NetStatus instance = new NetStatus();
    static Context context;
    ConnectivityManager connectivityManager;
    boolean connected = false;

    public static NetStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        boolean online = false;
        try {
            connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            connected = networkInfo != null && networkInfo.isAvailable() &&
                    networkInfo.isConnected();
            if (connected) {
                if (isInternetWorking()) online = true;
            }
        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return online;
    }

    public boolean isInternetWorking() {
        boolean success = false;
        try {
            URL url = new URL("http://www.google.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-Agent", "Android");
            connection.setRequestProperty("Connection", "close");
            connection.setConnectTimeout(1000);
            connection.setReadTimeout(1000);
            connection.connect();
            if (connection.getResponseCode() == 200) success = true;
            connection.disconnect();
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return success;
    }
}
于 2017-09-07T22:51:04.197 回答