4

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();
    
    }  }
 }
Laurel
  • 5,965
  • 14
  • 31
  • 57
Andrain
  • 872
  • 1
  • 16
  • 43

1 Answers1

9

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!!

Juan Aguilar Guisado
  • 1,687
  • 1
  • 12
  • 21
  • What is changed in this code? it looks same like mine – Andrain Jun 30 '15 at 06:46
  • Please tell me one thing this code will work for both 2G and 3G? – Andrain Jun 30 '15 at 06:49
  • There aren't important changes, but sometimes handling bad an exception or things like that can make you get crazy. I gave you an example that is working for me just in case you would only want to copy&paste to prove. I'm afraid I haven't check if it works with 2G and 3G, but check it. For making it work, I recommend you to test this with Wifi or 4G, because I can assure it works with them. – Juan Aguilar Guisado Jun 30 '15 at 07:00
  • Juan where to write throws IO Exception? with main activity or with doinbackground? – Andrain Jun 30 '15 at 07:21
  • I would catch it ASAP in your call order. In this case, en doinbackground. There, use your "Log.e .....". For making easier, filter in your logcat only the errors. Maybe it's printing but hiding for the other messages. – Juan Aguilar Guisado Jun 30 '15 at 07:26
  • Does this require INTERNET PERMISSIONS – Qadir Hussain Nov 01 '17 at 10:15
  • I think you should set the default timeout of the client, it seems that the default timeout is set to 0, which means indefinite, in the commons-net lib. – Raphael C Oct 16 '19 at 12:15