© Khmer Angkor Academy - sophearithput168

Activity

Activity អ្វីជា?

Activity គឺជា fundamental component មួយក្នុង Android ដែលតំណាងឱ្យ single screen with user interface។ វាគឺដូចជា "page" ឬ "window" មួយក្នុង application របស់អ្នក ដែល users អាច interact បាន។

� Analogy: Activity ដូចជា webpage នៅក្នុង website។ App មួយអាចមាន Activities ច្រើន (ដូចជា website មាន pages ច្រើន)។ Login page = LoginActivity, Home page = MainActivity, Settings page = SettingsActivity។

🎯 Activity Characteristics

Characteristic ពិពណ៌នា
Single Focused Task Activity មួយធ្វើ task តែមួយ (Login, Display list, Show details)
Independent Activity នីមួយៗ independent - អាច start ដោយឯករាជ្យ
Lifecycle Management Android system គ្រប់គ្រង Activity lifecycle
Back Stack Activities ត្រូវបាន stack ពីលើគ្នា (LIFO - Last In First Out)
State Restoration អាចរក្សាទុក និង restore state នៅពេល configuration change

📱 Activity Lifecycle (វដ្តជីវិតពេញលេញ)

Activity lifecycle គឺជា series នៃ callback methods ដែល Android system ហៅ នៅពេល Activity changes states។ យល់ដឹងអំពី lifecycle គឺសំខាន់ណាស់ដើម្បី៖

  • Manage resources efficiently - បិទ database connections, stop animations
  • Save/Restore user data - ពេល screen rotation ឬ app minimized
  • Prevent crashes - Handle null pointers, memory leaks
  • Optimize battery - Stop GPS, sensors នៅពេលមិនប្រើ
  • Improve UX - Pause video នៅពេល user leave app

🔄 Complete Lifecycle Flow

        [Activity Launched] 🚀
               │
               ▼
         ┌──────────┐
         │onCreate()│ ──► 📦 Initialize: setContentView, findViewById, variables
         └────┬─────┘     🔹 Called ONCE when Activity is created
              │            🔹 Restore saved instance state if available
              ▼
         ┌──────────┐
         │onStart() │ ──► 👁️ Activity becomes VISIBLE to user
         └────┬─────┘     🔹 Register BroadcastReceivers here
              │            🔹 Prepare animations, UI updates
              ▼
         ┌──────────┐
         │onResume()│ ──► ▶️ Activity in FOREGROUND - User can INTERACT
         └────┬─────┘     🔹 Start animations, play media
              │            🔹 Acquire exclusive resources (Camera, Sensors)
              ▼
      [🏃 RUNNING STATE] ◄─► User interacts with app
              │
      ┌───────┴───────┐
      │               │
[User leaves app] [Another Activity covers this one]
      │               │
      ▼               ▼
┌──────────┐    ┌──────────┐
│onPause() │    │onPause() │ ──► ⏸️ Activity LOSES FOCUS
└────┬─────┘    └────┬─────┘     🔹 Pause ongoing actions (animations, video)
     │                │            🔹 Save draft data (QUICK - < 1 second!)
     │                │            ⚠️ Don't do heavy operations here!
     ▼                │
┌──────────┐         │
│onStop()  │◄────────┘ ──► 🔇 Activity NO LONGER VISIBLE
└────┬─────┘              🔹 Save persistent data
     │                     🔹 Release resources (stop location updates)
     │                     🔹 Unregister receivers (if not needed)
     │
┌────┴────┐
│         │
│    [User returns]     [System needs memory/User exits]
│         │                    │
│         ▼                    ▼
│    ┌───────────┐        ┌──────────┐
│    │onRestart()│        │onDestroy()│ ──► 💀 Activity DESTROYED
│    └─────┬─────┘        └──────────┘     🔹 Final cleanup
│          │                                🔹 Close databases, threads
│          └──► Back to onStart()           🔹 Unregister all receivers
│
└──► [Activity Destroyed]

� Lifecycle Callback Methods - Detailed

Method State ធ្វើអ្វីនៅទីនេះ Next Callback
onCreate() Created ✅ setContentView()
✅ findViewById()
✅ Initialize variables
✅ Setup ViewModels
❌ Heavy operations
onStart()
onStart() Visible ✅ Register BroadcastReceivers
✅ Start animations
✅ Refresh UI data
onResume()
onResume() Foreground ✅ Start camera preview
✅ Play video/audio
✅ Register sensors
✅ Acquire exclusive resources
onPause()
onPause() Partially Visible ✅ Pause video/audio
✅ Save draft data
✅ Pause animations
⚠️ MUST be fast (< 1s)
onResume() or onStop()
onStop() Not Visible ✅ Save all data to database
✅ Stop location updates
✅ Release sensors
✅ Unregister receivers
onRestart() or onDestroy()
onRestart() Restarting ✅ Refresh data from server
✅ Reconnect to services
onStart()
onDestroy() Destroyed ✅ Close databases
✅ Stop threads
✅ Unregister ALL receivers
✅ Final cleanup
None (Activity ended)

⚠️ CRITICAL: onPause() ត្រូវតែរត់រហ័សលឿន (< 1 second) ព្រោះវារាំងការ navigate ទៅ Activity បន្ទាប់! មិនត្រូវធ្វើ network calls, database queries ទេ!

🎬 Common Lifecycle Scenarios

Scenario Lifecycle Flow
📱 Launch App onCreate() → onStart() → onResume()
🏠 Press Home Button onPause() → onStop()
🔙 Press Back Button onPause() → onStop() → onDestroy()
🔄 Return to App onRestart() → onStart() → onResume()
📞 Incoming Call onPause() [Call dialog on top]
🔄 Screen Rotation onPause() → onStop() → onDestroy() → onCreate() → onStart() → onResume()
💬 Dialog Appears onPause() [Activity partially visible]
💀 System Kills App (Low Memory) onPause() → onStop() → onDestroy() (if time permits)

💻 បង្កើត Activity

Java Code
Click "Run" to execute the Java code

📄 Layout File (activity_main.xml)

Java Code
Click "Run" to execute the Java code

🎯 findViewById() Method

ប្រើសម្រាប់ទាញយក reference នៃ View ពី layout:

Java Code
Click "Run" to execute the Java code

⚠️ សំខាន់: ត្រូវហៅ findViewById() បន្ទាប់ពី setContentView() ប៉ុណ្ណោះ!

✅ Best Practices

  1. ហៅ super methods នៅក្នុង lifecycle callbacks
  2. Initialize views នៅក្នុង onCreate()
  3. រក្សាទុកទិន្នន័យនៅក្នុង onPause()
  4. សម្អាត resources នៅក្នុង onDestroy()
  5. ប្រើ @Override annotation