Android 从互联网上获取实际时间?

Android 从互联网上获取实际时间?,android,datetime,time,Android,Datetime,Time,如果设备时间更改,如何以编程方式获取“当前(实际)时间”或“网络运营商时间” 我试图通过“LocationManager”类的“getLastKnownLocation”方法获取当前时间。但它给出了最后的定位时间,但我需要当前时间 有人能告诉我一个从互联网上获取实际时间的正确方法吗 如果可能,无需使用任何外部库 提前感谢。试试这个: System.currentTimeMillis(); 根据这一点,您可以从NTP服务器获取当前时间 support.ntp.org library 增加你

如果设备时间更改,如何以编程方式获取“当前(实际)时间”或“网络运营商时间”

我试图通过“LocationManager”类的“getLastKnownLocation”方法获取当前时间。但它给出了最后的定位时间,但我需要当前时间

有人能告诉我一个从互联网上获取实际时间的正确方法吗

  • 如果可能,无需使用任何外部库
提前感谢。

试试这个:

System.currentTimeMillis();
根据这一点,您可以从NTP服务器获取当前时间

support.ntp.org library
增加你的依赖性

String timeServer = "server 0.pool.ntp.org";
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(timeServer);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
long returnTime = timeInfo.getReturnTime();
System.out.println(returnTime)

例如,您可以使用geo names提供的rest完整api,它需要lat和long

对于Android:

添加到gradle应用程序模块:

compile 'commons-net:commons-net:3.3'
添加到您的代码中:

...
String TAG = "YOUR_APP_TAG";
String TIME_SERVER = "0.europe.pool.ntp.org";
...
public void checkTimeServer() {
    try {
        NTPUDPClient timeClient = new NTPUDPClient();
        InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);
        long setverTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();

        // store this somewhere and use to correct system time
        long timeCorrection = System.currentTimeMillis()-setverTime;    
    } catch (Exception e) {
        Log.v(TAG,"Time server error - "+e.getLocalizedMessage());
    }
}

注意:前面的回答中提到的timeInfo.getReturnTime()将为您获取本地系统时间,如果您需要服务器时间,则必须使用timeInfo.getMessage().getTransmitTimeStamp().getTime()。

从第三方服务器获取时间在大多数情况下是不可靠的,其中一些是付费服务

如果您想获得准确的时间,并用手机检查它是否正确,无论使用何种方法,您都可以使用以下简单技巧获得实际时间

private class GetActualTime extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {
            try {
                HttpURLConnection urlConnection = null;
                StringBuilder result = new StringBuilder();
                try {
                    URL url = new URL(urls[0]);
                    urlConnection = (HttpURLConnection) url.openConnection();
                    int code = urlConnection.getResponseCode();
                    if (code == 200) {
                        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                        String line = "";
                        while ((line = bufferedReader.readLine()) != null)
                        result.append(line);
                        in.close();
                    }
                        else {
                        return "error on fetching";
                    }
                    return result.toString();
                } catch (MalformedURLException e) {
                    return "malformed URL";
                } catch (IOException e) {
                   return "io exception";
                } finally {
                    if (urlConnection != null) {urlConnection.disconnect();
                    }
                }
            } catch (Exception e) { return "null"; }
        }

        @Override
        protected void onPostExecute(String time) {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat mdformat = new SimpleDateFormat("h:mm");
            String times =  mdformat.format(calendar.getTime());
            try {
                String areatime = time.substring(time.indexOf(String.valueOf(times)), time.indexOf(String.valueOf(times)) + 5).trim(); 
                        Toast.makeText(this, "The actual time is " + areatime, Toast.LENGTH_SHORT).show();

            }
            catch(IndexOutOfBoundsException e){
                        Toast.makeText(this, "Mobile time is not same as Internet time", Toast.LENGTH_SHORT).show();
                }
            }


        }

    }
所以这实际上是从谷歌那里得到的时间。这在我的项目中非常有效。为了检查系统时间是否错误,可以使用此技巧。你可以信任谷歌,而不是依赖时间服务器


由于它在检查时更加敏感,因此即使提前一分钟或延迟一分钟也会捕获异常。如果你想处理这个问题,你可以自定义代码。

你看起来不够努力,这似乎是感谢@Kiloreux。已经提到了这个链接。但我需要时间而不使用库。你可以看看这个系统。currentTimeMillis();为您提供当前设备的时间,而不是来自internet的时间。您手机的时间是internet的实际时间如果您通过设置修改该时间,则它不是internet的实际时间OK,因此您必须从服务器请求时间,如下所示:这是非常有用的rest api。我可以无限次调用此web服务吗?或任何限制?并创建您自己的帐户:D username=adeel_turk是我的;)如果你认为你得到了答案,那么请接受它已经创建了我自己的帐户。别担心,我没有用你的:)。顺便说一句,谢谢。我很高兴帕特尔先生:)这并没有给你网络运营商的时间,而是全球NTP池中NTP服务器的当前时间。
new GetActualTime().execute("https://www.google.com/search?q=time");