การเปิด Activity เฉพาะครั้งแรกที่เปิดแอป (First Launch Only)
ตัวอย่างนี้สาธิตวิธีใช้ SharedPreferences เพื่อตรวจสอบว่าเป็นครั้งแรกที่เปิดแอปหรือไม่ หากไม่ใช่ จะปิด Activity ทันที
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio เลือก File → New Project และกรอกข้อมูลที่จำเป็น
ขั้นตอนที่ 2: จัดทำ Layout (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="Activity นี้จะเปิดได้เพียงครั้งเดียว" />
</LinearLayout>
ขั้นตอนที่ 3: เขียนโค้ดหลัก (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)) {
// ครั้งแรกที่เปิด
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(prevStarted, true);
editor.apply();
} else {
// ไม่ใช่ครั้งแรก -> ปิด Activity
finish();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
ขั้นตอนที่ 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>
การทดสอบ
รันแอปครั้งแรก จะแสดง Activity นี้ รันครั้งที่สองขึ้นไป Activity จะปิดทันที (finish)

การประยุกต์ใช้
เหมาะสำหรับหน้าจอ Welcome, Tutorial, Login หรือ Terms of Service ที่ต้องการแสดงแค่ครั้งแรก