Mục tiêu
Xác định xem ứng dụng đang được mở lần đầu tiên sau khi cài đặt hay không, để hiển thị màn hình hướng dẫn (onboarding), thiết lập mặc định, v.v.
Cách tiếp cận
Sử dụng SharedPreferences lưu trữ một cờ boolean firstTime. Lần đầu chạy, giá trị mặc định là true, sau đó set thành false.
Các bước thực hiện
Bước 1: Tạo dự án mới
Android Studio → File → New Project → Empty Activity.
Bước 2: Layout đơn giản (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvFirstTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Bước 3: Logic trong MainActivity.java
package com.example.firsttimercheck;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private TextView tvFirstTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvFirstTime = findViewById(R.id.tvFirstTime);
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
if (isFirstTime()) {
tvFirstTime.setText("🎉 Chào mừng! Đây là lần đầu bạn mở ứng dụng.");
} else {
tvFirstTime.setText("👋 Chào lại bạn! Đây không phải lần đầu tiên.");
}
}
private boolean isFirstTime() {
boolean firstTime = sharedPreferences.getBoolean("firstTime", true);
if (firstTime) {
editor.putBoolean("firstTime", false);
editor.apply(); // apply() bất đồng bộ, hiệu năng tốt hơn commit()
return true;
}
return false;
}
}
Giải thích quan trọng
getPreferences(MODE_PRIVATE): Lấy SharedPreferences riêng của Activity (tên file = tên class Activity)getBoolean("firstTime", true): Giá trị mặc định làtrue(chưa từng chạy)editor.apply(): Ghi bất đồng bộ, không block UI thread. Nên dùng thay vìcommit()(đồng bộ)- Không cần gọi cả
commit()vàapply()- chỉ cầnapply()là đủ
Cải tiến cho ứng dụng thực tế
Trong production, nên dùng getSharedPreferences("app_prefs", MODE_PRIVATE) ở cấp Application để chia sẻ giữa nhiều Activity/Fragment, và xử lý trường hợp người dùng xóa dữ liệu ứng dụng (cờ sẽ reset về true).
Kết quả
Lần đầu chạy: Hiển thị "Chào mừng! Đây là lần đầu..."
Các lần sau: Hiển thị "Chào lại bạn! Đây không phải lần đầu..."

