Giới thiệu
Hướng dẫn này trình bày cách hiển thị một Activity (như màn hình chào, hướng dẫn) chỉ một lần khi người dùng mở ứng dụng lần đầu tiên, sử dụng SharedPreferences để lưu trạng thái.
Các bước thực hiện
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project và đ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"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Màn hình này chỉ hiển thị một lần" />
</LinearLayout>
Bước 3: Viết logic xử lý (src/MainActivity.java)
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
String prevStarted = "prevStarted";
@Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
if (!sharedPreferences.getBoolean(prevStarted, false)) {
// Lần đầu chạy: lưu trạng thái và hiển thị
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(prevStarted, true);
editor.apply();
} else {
// Đã chạy rồi: đóng Activity này
finish();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Bước 4: Cấu hình Manifest (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>
Giải thích
- Sử dụng
onResume()thay vìonCreate()để đảm bảo kiểm tra mỗi khi Activity xuất hiện SharedPreferenceslưu trữ cờ booleanprevStarted- Lần đầu: cờ = false → set true và hiển thị
- Lần sau: cờ = true → gọi
finish()để đóng Activity
Chạy ứng dụng
Kết nối thiết bị Android, nhấn Run trong Android Studio. Lần đầu sẽ hiển thị màn hình, lần sau sẽ tự đóng ngay lập tức.
