Giới thiệu
Ví dụ này minh họa cách lấy giờ hiện tại (local time) trong Android sử dụng lớp LocalTime từ API java.time (yêu cầu API level 26 / Android 8.0+).
Bước 1: Tạo project mới
Mở Android Studio, chọn File → New Project, điền thông tin cần thiết.
Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Giờ địa phương"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Chỉ cần một TextView để hiển thị giờ.
Bước 3: Code MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.time.LocalTime;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.date);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
LocalTime time = LocalTime.now();
textView.setText("Giờ: " + time);
}
}
}
Lưu ý: Kiểm tra phiên bản Android (SDK_INT >= O) vì java.time chỉ khả dụng từ API 26. Với các phiên bản cũ hơn, hãy dùng thư viện ThreeTenABP hoặc Calendar.
Chạy ứng dụng
Kết nối thiết bị, nhấn Run trong Android Studio. Màn hình sẽ hiển thị giờ hiện tại kèm giây.
