如何获得时间从网络上Android的中 [英] How to get time from Network in Android

查看:448
本文介绍了如何获得时间从网络上Android的中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用我想使用网络时间而非设备的时间。这是那个时候应该是正确的我的应用程序的要求。

我试图从获取时间 NTS服务器,但装载机继续运行,并不会停止我等了30多分钟,但我仍然没有得到任何东西。

我想知道有没有其他的方法从网络获取,因为我没有得到来自网络时间的事情需要这么多的时间。

 公共类MainActivity延伸活动{公共静态最后弦乐TIME_SERVER =time-a.nist.gov;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    按钮btnGetTime =(按钮)findViewById(R.id.button1);     btnGetTime.setOnClickListener(新View.OnClickListener(){
        公共无效的onClick(视图v){
            //执行上的点击动作
              新GetTimeFromNetwork()执行();
        }
    });   } 公共类GetTimeFromNetwork扩展的AsyncTask<弦乐,太虚,字符串> {    ProgressDialog progressDialog;    @覆盖
    在preExecute保护无效(){        progressDialog =新ProgressDialog(MainActivity.this);
        progressDialog.setMessage(正在加载...);
        progressDialog.setCancelable(假);
        progressDialog.show();
        Log.i(pre执行,是);    }
    @覆盖
    保护字符串doInBackground(字符串... PARAMS){
        // TODO自动生成方法存根
    Log.i(在获取时间从服务器类,是);           尝试{
                NTPUDPClient timeClient =新NTPUDPClient();
                InetAddress类InetAddress类= InetAddress.getByName(TIME_SERVER);
                TimeInfo timeInfo = timeClient.getTime(InetAddress类);
                //长返回时间= timeInfo.getReturnTime(); //本地设备的时间
                长返回时间= timeInfo.getMessage()。getTransmitTimeStamp()
                        .getTime(); //服务器时间
                日期时间=新的日期(返回时间);
                Log.i(时间,+ TIME_SERVER +从时间:+时间);
            }赶上(例外五){
                // TODO:处理异常
                Log.e(错误,e.getMessage());
         }
              返回null;
    }    @覆盖
    保护无效onPostExecute(字符串结果){
        super.onPostExecute(结果);
        progressDialog.dismiss();    }}
 }


解决方案

此解决方案是为我工作:

这种依赖关系(也许你已经拥有它)进口在你的模块gradle这个:

 编译公地网:公网:3.3

下面你所得到的本地/网络时间的样本。如你所知,你应该在一个异步的任务,因为你与你的解决方案没有运行。

 公共静态最后弦乐TIME_SERVER =time-a.nist.gov;公共静态无效printTimes()抛出IOException
            NTPUDPClient timeClient =新NTPUDPClient();
            InetAddress类InetAddress类= InetAddress.getByName(TIME_SERVER);
            TimeInfo timeInfo = timeClient.getTime(InetAddress类);
            //长返回时间= timeInfo.getReturnTime(); //本地设备的时间
            长返回时间= timeInfo.getMessage()getTransmitTimeStamp()的getTime()。 //服务器时间            日期时间=新的日期(返回时间);
            Log.e(getCurrentNetworkTime+ TIME_SERVER +从时间:+时间);            Log.e(本地时间,当地时间);
            Log.e(本地时间,当前时间:+新的Date(System.currentTimeMillis的()));
            Log.e(当地时间,时间的信息:+新的日期(timeInfo.getReturnTime()));
            Log.e(本地时间,GetOriginateTimeStamp:。+新的日期(timeInfo.getMessage()getOriginateTimeStamp()的getTime()));            Log.e(NTP时间,+ TIME_SERVER +从时间:+时间);            Log.e(当地时间,时间的信息:+新的日期(timeInfo.getMessage()getReceiveTimeStamp()的getTime()));
            Log.e(本地时间,GetOriginateTimeStamp:。+新的日期(timeInfo.getMessage()getTransmitTimeStamp()的getTime()));        }

摘要只得到你的净时间:

 公共静态长getNetworkTime()抛出IOException
        NTPUDPClient timeClient =新NTPUDPClient();
        InetAddress类InetAddress类= InetAddress.getByName(TIME_SERVER);
        TimeInfo timeInfo = timeClient.getTime(InetAddress类);
        返回timeInfo.getMessage()getReceiveTimeStamp()的getTime()。
    }

我希望这有助于!

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.

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

    }  }
 }

解决方案

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

这篇关于如何获得时间从网络上Android的中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆