javaandroidandroid-networking

How to get time from Network in Android


In my app, I want to use the Network Time and not the time of the device. It is the requirement of my app that time should be correct.

I'm trying to get the time from NTS server but the loader keeps on running and does not stop. I waited for more than 30 mins but still I don't get anything.

I want to know is there any other method for getting the from the network because I don't think getting time from network takes so much time.

public class MainActivity extends Activity  {

public static final String TIME_SERVER = "time-a.nist.gov";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnGetTime = (Button)findViewById(R.id.button1);
    
     btnGetTime.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click 
              new GetTimeFromNetwork().execute();
        }
    });

   }
    
 public class GetTimeFromNetwork extends AsyncTask<String, Void, String> {
    
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        Log.i( "pre execute","yes"); 

    }


    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
    Log.i("In Get time From Server class", "yes");

           try {
                NTPUDPClient timeClient = new NTPUDPClient();
                InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
                TimeInfo timeInfo = timeClient.getTime(inetAddress);
                //long returnTime = timeInfo.getReturnTime();   //local device time
                long returnTime = timeInfo.getMessage().getTransmitTimeStamp()
                        .getTime(); //server time
                Date time = new Date(returnTime);
                Log.i("time", "Time from " + TIME_SERVER + ": " + time);
            } catch (Exception e) {
                // TODO: handle exception
                Log.e("error",e.getMessage());
         }
              return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        progressDialog.dismiss();
    
    }  }
 }

Solution

  • This solution is working for me:

    Import in your module gradle this dependency (maybe you already have it):

    compile 'commons-net:commons-net:3.3'
    

    Here you are a sample getting the local/net time. As you know, you should run it in an Async task as you did with your solution.

    public static final String TIME_SERVER = "time-a.nist.gov";
    
    public static void printTimes() throws IOException {
                NTPUDPClient timeClient = new NTPUDPClient();
                InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
                TimeInfo timeInfo = timeClient.getTime(inetAddress);
                //long returnTime = timeInfo.getReturnTime();   //local device time
                long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();   //server time
    
                Date time = new Date(returnTime);
                Log.e("getCurrentNetworkTime", "Time from " + TIME_SERVER + ": " + time);
    
                Log.e("Local time", "Local time");
                Log.e("Local time", "Current time: " + new Date(System.currentTimeMillis()));
                Log.e("Local time", "Time info: " + new Date(timeInfo.getReturnTime()));
                Log.e("Local time", "GetOriginateTimeStamp: " + new Date(timeInfo.getMessage().getOriginateTimeStamp().getTime()));
    
                Log.e("NTP time", "Time from " + TIME_SERVER + ": " + time);
    
                Log.e("Local time", "Time info: " + new Date(timeInfo.getMessage().getReceiveTimeStamp().getTime()));
                Log.e("Local time", "GetOriginateTimeStamp: " + new Date(timeInfo.getMessage().getTransmitTimeStamp().getTime()));
    
            }
    

    Summary getting only your net time:

    public static long getNetworkTime() throws IOException {
            NTPUDPClient timeClient = new NTPUDPClient();
            InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
            TimeInfo timeInfo = timeClient.getTime(inetAddress);
            return timeInfo.getMessage().getReceiveTimeStamp().getTime();
        }
    

    I hope this helps!!