Android 如何从网络获取时间

How to get time from Network in Android

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

我正在尝试从 NTS 服务器 获取时间,但加载程序一直在 运行 并且没有停止我等了超过 30 分钟但我仍然没有得到任何东西。

我想知道是否有任何其他方法可以从网络获取时间,因为我不认为从网络获取时间需要那么多时间。

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

    }  }
 }

这个解决方案对我有用:

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

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

这是获得 local/net 时间的示例。如您所知,您应该 运行 在异步任务中使用您的解决方案。

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

        }

仅获取您的净时间的摘要:

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

希望对您有所帮助!!