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();
} }
}