2

In my android application I need to connect to the internet to check for the time. This snippet works very nicely in mobile networks and in WiFi-Networks with no proxy enabled:

public class MyTimeGetterTask {
    @Override
    protected Long doInBackground(Void... params) {
        WebTimeSntpClient client = new WebTimeSntpClient();
        if (client.requestTime("time-d.nist.gov", 3000)) {
            long now = client.getNtpTime() + SystemClock.elapsedRealtime()
                - client.getNtpTimeReference();
            return now;
        }
        else {
            return null;
        }
    }
}

The core elements of the WebTimeSntpClient are as follows:

public class WebTimeSntpClient {
    public boolean requestTime(String host, int timeout) {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();
            socket.setSoTimeout(timeout);
            InetAddress address = InetAddress.getByName(host);
            byte[] buffer = new byte[NTP_PACKET_SIZE];
            DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);

            ...   

            socket.send(request);

            DatagramPacket response = new DatagramPacket(buffer, buffer.length);
            socket.receive(response);
            ...

        } catch (IOException ex) {
            return false;
        } finally {
            if (socket != null) {
                socket.close();
            }
        }

        return true;
    }
}

However when I'm in the office and the WiFi requires me to configure a proxy (which I did in the settings by long-pressing on the network and then clicking "modify network" - as of Android API level 17) the connection fails.

Now I have looked up quite a lot of very good posts about proxies on the internet and especially here on SO, but absolutely none of them seem to answer this (to me) very simple question:

How do I force my application to use the proxy that is already configured in the settings?

Instead, they focus on more advanced issues like:

Again: I want to stress that this is not my intention, I simply want my app to connect to the internet, no matter what. Is there some System.useWifiProxyIfAvailable(true) method? I'm sure I must have missed a post somewhere here...

Community
  • 1
  • 1
avalancha
  • 1,457
  • 1
  • 22
  • 41

1 Answers1

1

You are trying to use SNTP trough a proxy that only allows HTTP/HTTPS. Your alternative is to use some HTTP service providing the current time, which will be more than enough for most user level applications.

Give http://www.timeapi.org/utc/now a try, however if you are publishing an application using this service you should check the terms and conditions.

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134