Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

android - Check real internet connection

In my application I need to check whether device is connected to Internet. I tried using ConnectivityManager but it doesn't give a 100% precise result. For instance, I might have a wi-fi connection but still don't have access to internet resources. In my case I've got to open a VPN connection, after I've connected to via wi-fi, in order to get real access to Internet. So the approach with ConnectivityManager doesn't work.

So, regarding the above - should I write a manual http request in order to ensure or there's another way ?

Here's some code I'm using

ConnectivityManager cm =  (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected() && cm.getActiveNetworkInfo().isAvailable();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you are correct, to check that you can reach the internet you need to test that explicitly. If you need HTTP access you can try connecting to the host you later on want to connect to.

You should however use the connection method that you intend to use later on. HTTP can work but not FTP. So if you need FTP access you should test it.


If you also want to get the external IP you can use this method:

public static InetAddress getExternalIp() throws IOException {
    URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("Protocol", "Http/1.1");
    connection.addRequestProperty("Connection", "keep-alive");
    connection.addRequestProperty("Keep-Alive", "1000");
    connection.addRequestProperty("User-Agent", "Web-Agent");

    Scanner s = new Scanner(connection.getInputStream());
    try {
        return InetAddress.getByName(s.nextLine());
    } finally {
        s.close();
    }
}

If you successfully got an IP address back from this method, you can connect via HTTP to that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...