Giới thiệu
Bài viết minh họa cách lấy ngày giờ hiện tại từ Internet (Network Time) thay vì dùng giờ hệ thống thiết bị (có thể sai do người dùng chỉnh tay). Lưu ý: Code mẫu gốc chỉ dùng Calendar local, chưa thực sự lấy từ Internet. Dưới đây là cách đúng.
Các bước thực hiện (Code mẫu gốc - chỉ local)
Bước 1: Tạo dự án mới
Khởi tạo project Android Studio.
Bước 2: Giao diện (res/layout/activity_main.xml)
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="168dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
android:text="Nhấn để lấy ngày giờ hiện tại"
android:textColor="@color/colorPrimary"/>
</RelativeLayout>
Bước 3: MainActivity (src/MainActivity.java) - Chỉ dùng giờ local
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Calendar calendar;
SimpleDateFormat simpleDateFormat;
String date;
TextView displayDateTime;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayDateTime = findViewById(R.id.textView);
btn = findViewById(R.id.button);
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
date = simpleDateFormat.format(calendar.getTime());
btn.setOnClickListener(v -> displayDateTime.setText(date));
}
}
Bước 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Chạy ứng dụng (phiên bản local)
Kết nối thiết bị, nhấn Run. Nhấn Button → hiển thị giờ hệ thống thiết bị.


⚡ Cách LẤY GIỜ TỪ INTERNET (Thực tế)
Code mẫu trên KHÔNG lấy giờ từ Internet. Dưới đây là cách đúng:
Cách 1: SNTP Client (Simple Network Time Protocol) - Khuyên dùng
// Thêm dependency: implementation 'com.google.android.gms:play-services-base:18.0.1'
// Hoặc dùng thư viện: implementation 'com.github.pavel163:Android-SNTP-Client:1.0.0'
// Sử dụng SNTPClient (cần thread riêng/AsyncTask/Coroutine)
SntpClient client = new SntpClient();
if (client.requestTime("time.google.com", 3000)) {
long now = client.getNtpTime(); // milliseconds since epoch
Date date = new Date(now);
// Format và hiển thị
}
Cách 2: HTTP Date Header (đơn giản, không cần thư viện)
// Chạy trên background thread (Coroutine/RxJava/AsyncTask)
private void fetchNetworkTime() {
new Thread(() -> {
try {
URL url = new URL("https://www.google.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
conn.connect();
long serverTimeMillis = conn.getDate(); // milliseconds since epoch
if (serverTimeMillis > 0) {
runOnUiThread(() -> {
Date date = new Date(serverTimeMillis);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault());
displayDateTime.setText("Network Time: " + sdf.format(date));
});
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
Cách 3: Google Play Services Time API (đáng tin cậy nhất)
// build.gradle: implementation 'com.google.android.gms:play-services-base:18.0.1' FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); // Hoặc dùng Time API nếu có (cần check availability) // Hiện tại Google không public Time API riêng, thường dùng SNTP
So sánh
| Phương pháp | Độ chính xác | Phức tạp | Yêu cầu mạng |
|---|---|---|---|
| System.currentTimeMillis() | Thấp (user chỉnh được) | Dễ | Không |
| HTTP Date Header | Trung bình (~giây) | Trung bình | Có |
| SNTP/NTP | Cao (ms) | Cao | Có |
| GPS Time | Rất cao | Cao | GPS |
Lưu ý quan trọng
- Luôn chạy network request trên background thread (không phải main thread)
- Cần quyền
INTERNETtrong Manifest - Xử lý timeout, retry, fallback về giờ local nếu mạng lỗi
- Cache kết quả để không request liên tục
- Đối với app ngân hàng/chứng khoán: bắt buộc dùng NTP/SNTP server tin cậy