Android开发之使用网络时间

使用truetime-android第三方库实现

github地址:https://github.com/instacart/truetime-android

配置教程

详见:github的wiki,也可阅读本文实例教程。

Add this to your application’s build.gradle file:

1
2
3
4
5
6
7
8
9
10
11
12
13
repositories {
maven {
url "https://jitpack.io"
}
}

dependencies {
// ...
implementation 'com.github.instacart.truetime-android:library-extension-rx:<release-version>'

// or if you want the vanilla version of Truetime:
implementation 'com.github.instacart.truetime-android:library:<release-version>'
}

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
allprojects {
repositories {
google()
jcenter()
maven {
url "https://jitpack.io"
}
}

}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'com.github.instacart.truetime-android:library:3.3'
}

Importing ‘com.github.instacart.truetime-android:library:‘ should be sufficient for this.

Then you must initialize it in onCreate() in your class that extendsandroid.app.Application.

1
TrueTime.build().initialize();

例子:

APP.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();

new Thread(new Runnable() {
@Override
public void run() {
try {
TrueTime.build().withNtpHost("time.ustc.edu.cn").initialize();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

}
}

将APP.java添加到AndroidManifest.xml

1
2
3
<application
android:name=".App"
</application>

使用Date noReallyThisIsTheTrueDateAndTime = TrueTime.now();来获取网络时间。