如何从Android中的网络中获取时间

时间:2021-12-30 16:03:14

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

在我的应用程序中,我想使用网络时间而不是设备的时间。我的应用程序要求时间应该是正确的。

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

我正试图从NTS服务器获得时间,但加载器继续运行并且不停止我等待超过30分钟,但我仍然没有得到任何东西。

I want to know is there any other method for getting the from network because I don't thing 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();

    }  }
 }

1 个解决方案

#1


5  

This solution is working for me:

这个解决方案对我有用:

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

在你的模块中导入gradle这个依赖(也许你已经拥有它):

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

我希望这有帮助!!

#1


5  

This solution is working for me:

这个解决方案对我有用:

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

在你的模块中导入gradle这个依赖(也许你已经拥有它):

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

我希望这有帮助!!