© Khmer Angkor Academy - sophearithput168

Services & Background Tasks

Services & Background Tasks

Services គឺជា components ដែលដំណើរការ long-running operations នៅ background ដោយមិនមាន UI។

🔄 ប្រភេទ Services

Service Type ពិពណ៌នា ពេលណាប្រើ
Foreground Service User ដឹង (មាន notification) Music player, Download, GPS tracking
Background Service User មិនដឹង Sync data, Clean cache
Bound Service បញ្ជា bind ទៅ component Client-server interaction

📱 Service Lifecycle

┌──────────────┐
│  onCreate()  │  ──► Service បង្កើតលើកដំបូង
└──────┬───────┘
       │
┌──────▼───────────┐
│ onStartCommand() │  ──► Service ចាប់ផ្តើម
└──────┬───────────┘
       │
   [Running]     ◄─► Service ដំណើរការ
       │
┌──────▼───────┐
│ onDestroy()  │  ──► Service បញ្ចប់
└──────────────┘

🎵 Started Service Example

Java Code
Click "Run" to execute the Java code

🎯 ចាប់ផ្តើម និងបញ្ឈប់ Service

Java Code
Click "Run" to execute the Java code

📢 Foreground Service

Foreground Service ត្រូវបង្ហាញ notification ដល់ user។

Java Code
Click "Run" to execute the Java code

⚙️ WorkManager (Recommended)

WorkManager គឺជាវិធី recommended សម្រាប់ background tasks ដែល guaranteed execution។

Java Code
Click "Run" to execute the Java code

🔗 Bound Service

Java Code
Click "Run" to execute the Java code

📋 Declare Service in Manifest

Java Code
Click "Run" to execute the Java code

💡 Important: Android 8.0+ មានការកំណត់លើ background services។ ប្រើ WorkManager ឬ Foreground Service វិញ!

✅ Best Practices

  1. ប្រើ WorkManager សម្រាប់ deferrable background work
  2. ប្រើ Foreground Service សម្រាប់ user-initiated tasks
  3. បញ្ឈប់ Service នៅពេលការងារបញ្ចប់
  4. មិនត្រូវធ្វើ heavy operations នៅលើ main thread
  5. Handle battery optimization properly