找到是否有一个活跃的互联网连接java android

时间:2017-08-14 05:04:43

标签: java android connection inetaddress android-connectivitymanager

我试图找出我的应用中是否存在有效的互联网连接。 我需要知道我是否可以在没有任何错误的情况下访问网络,有时我会得到" true"即使我没有互联网连接也是如此,因为我仍然连接到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仿真器和实际设备上进行测试,因为我试图访问网络,即使我已经离线"。

寻求帮助! 非常感谢你。

3 个答案:

答案 0 :(得分: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);
    }

答案 1 :(得分: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;
    }
}

答案 2 :(得分: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;
    }
}