Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

ความแตกต่างระหว่าง onCreate() และ onStart() ใน Android

ความแตกต่างระหว่าง 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>

ความแตกต่างสำคัญ

ลำดับ Activity Lifecycle เต็มรูปแบบ

onCreate()       → สร้างครั้งแรก, setContentView, init data
    ↓
onStart()        → เริ่มมองเห็น (แต่ยังไม่โต้ตอบได้)
    ↓
onResume()       → Foreground, โต้ตอบได้, เริ่ม Animation
    ↑            ↑
    │            └── User กลับมาที่ App (จาก Home, App อื่น)
    │                 เรียก onRestart() → onStart() → onResume()
    │
onPause()        → เริ่มหาย (Dialog, Multi-window, Back Pressed)
    ↓
onStop()         → หายจากมุมมองเลย
    ↓
onDestroy()      → ทำลาย Activity
    ↓
(onCreate() ใหม่ถ้าเปิดใหม่)

สถานการณ์ที่ onStart เรียกแต่ onCreate ไม่เรียก

  • กด Home → กลับมาที่ App
  • เปิด Dialog/Activity ใหม่ทับ → ปิด Dialog/Back
  • Multi-window: ย้าย Focus ไป App อื่น → กลับมา
  • Screen Off → Screen On (บาง Device)
  • onRestart() → onStart() → onResume()

Best Practice: ทำอะไรในแต่ละ Method

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);  // ✅ UI Setup
    // ✅ Init Views, ViewModel, Adapters
    // ✅ Restore State from savedInstanceState
    // ✅ One-time Setup (Database, Receivers สำหรับ Process-wide)
}

@Override
protected void onStart() {
    super.onStart();
    // ✅ Register Listeners (EventBus, BroadcastReceiver)
    // ✅ Start Animations
    // ✅ Check Permissions (ถ้ายังไม่ได้)
    // ✅ Resume Sensors, Location Updates
}

@Override
protected void onResume() {
    super.onResume();
    // ✅ Resume Camera, Audio Focus
    // ✅ Start Foreground-only Work
}

@Override
protected void onPause() {
    super.onPause();
    // ✅ Pause Camera, Release Audio Focus
    // ✅ Save Unsaved Data (Quick)
    // ❌ ไม่ควรทำงานหนัก/Network
}

@Override
protected void onStop() {
    super.onStop();
    // ✅ Unregister Listeners
    // ✅ Stop Animations
    // ✅ Save Persistent Data (SharedPrefs, DB)
}

@Override
protected void onDestroy() {
    super.onDestroy();
    // ✅ Cleanup: Unregister Receivers, Close Cursors, Stop Services
    // ❌ ไม่ควร Save Critical Data (อาจไม่ถูกเรียก)
}

การทดสอบ

รันแอป → ดู Logcat Tag "Have a nice day!" → จะเห็น onCreate แล้ว onStart → กด Home → กลับมา → จะเห็น onRestart, onStart, onResume (ไม่มี onCreate)

คุณสมบัติ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 มองเห็นแล้ว)