ความแตกต่างระหว่าง onCreate() และ onStart() ใน Activity Lifecycle
ตัวอย่างนี้แสดงความแตกต่างระหว่าง onCreate() (สร้าง Activity ครั้งแรก) และ onStart() (Activity เริ่มมองเห็นได้) พร้อม Log เพื่อดูลำดับการทำงาน
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → File → New Project → กรอกรายละเอียด → Finish
ขั้นตอนที่ 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"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Have a very nice day!"
android:textSize="35dp"
android:textStyle="bold"
android:textColor="@color/colorAccent"
android:layout_centerInParent="true"
android:padding="20sp"
android:layout_gravity="center_vertical" />
</LinearLayout>
ขั้นตอนที่ 3: MainActivity.java
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
public static final String TAG = "Have a nice day!";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "onCreate");
}
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "onStart");
}
}
ขั้นตอนที่ 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>
ความแตกต่างสำคัญ
| คุณสมบัติ | onCreate() | onStart() |
|---|---|---|
| ถูกเรียกเมื่อ | Activity ถูกสร้างครั้งแรก | Activity เริ่มมองเห็นได้ (Visible) |
| ความถี่ | ครั้งเดียวตลอดชีวิต Instance | หลายครั้ง (ทุกครั้งที่กลับมามองเห็น) |
| Bundle savedInstanceState | มี (อาจเป็น null) | ไม่มี |
| UI Initialization | ✅ ใช่ (setContentView, findViewById) | ❌ ไม่ควร (UI พร้อมแล้ว) |
| Data Restoration | ✅ ใช่ (restore from Bundle) | ❌ ไม่จำเป็น |
| Register Listeners/Receivers | ✅ ใช่ | ✅ ใช่ (ถ้ายังไม่ได้ลงทะเบียน) |
| Start Animations | ❌ ยังไม่มองเห็น | ✅ ใช่ (User มองเห็นแล้ว) |