Android Service क्या है? | Types, Lifecycle, Foreground Service, Code (Hindi)

Android Service क्या है? (Full Guide in Hindi)

Types • Lifecycle • Foreground Service • Bound Service • Best Practices • Java Code Examples

Android Studio • Java

Service in Android: आसान शब्दों में

Service Android का application component है जो बिना UI के background में काम करता है—जैसे music play करना, files डाउनलोड/अपलोड करना, या location ट्रैक करना। Activity बंद होने पर भी Service चल सकती है (use-case पर निर्भर)।

कब उपयोग करें? जब काम UI के बिना हो सकता हो, लंबे समय तक चलना हो, और विश्वसनीय रूप से पूरा होना ज़रूरी हो।

Table of Contents

Service के Types

1) Foreground Service

एक persistent notification दिखाता है। High-priority tasks (music, fitness, navigation) के लिए।

2) Background Service

सीधे background में। लेकिन नए Android versions में काफी restrictions हैं। लंबे/deferrable tasks के लिए WorkManager बेहतर है।

3) Bound Service

जब किसी client (Activity/Fragment) को service से bind होकर interaction चाहिए—जैसे media controls, internal IPC।

Quick Compare
  • UI: नहीं
  • Long-running: हाँ
  • User-visible work: Foreground Service
  • Reliable deferrable work: WorkManager
ध्यान दें: Android 8.0+ में background execution limits हैं—सीधे background service start करने पर restrictions/ANR/kill हो सकता है।

Service Lifecycle

Started Service Flow

startService() → onCreate() → onStartCommand() → (running) → stopSelf()/stopService() → onDestroy()

Bound Service Flow

bindService() → onCreate() → onBind() → (client bound) → onUnbind() → onDestroy() [यदि कोई client न बचे]

मुख्य callbacks: onCreate(), onStartCommand(), onBind(), onUnbind(), onDestroy()

Simple Service (Java) — Started/Unbound

package com.example.myserviceapp;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {

  @Override
  public void onCreate() {
    super.onCreate();
    Toast.makeText(this, "Service Created", Toast.LENGTH_SHORT).show();
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();

    // TODO: अपना background task यहाँ चलाएँ (thread/Executor का उपयोग करें)
    // इस उदाहरण में हम START_STICKY लौटा रहे हैं ताकि system kill के बाद पुनः शुरू हो सके।
    return START_STICKY;
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null; // Unbound/Started service के लिए null
  }
}
Heavy work को main thread पर न चलाएँ। Thread/Executor/Coroutine (Kotlin) का उपयोग करें।

Foreground Service + NotificationChannel (API 26+)

package com.example.myserviceapp;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import androidx.core.app.NotificationCompat;

public class MyForegroundService extends Service {

  private static final String CHANNEL_ID = "my_fg_channel";

  @Override
  public void onCreate() {
    super.onCreate();
    createChannelIfNeeded();
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setContentTitle("Processing in background")
        .setContentText("Your task is running…")
        .setSmallIcon(android.R.drawable.stat_notify_sync)
        .setOngoing(true)
        .build();

    startForeground(101, notification);

    // TODO: अपना long-running task यहाँ start करें (Worker/Thread)
    // काम पूरा होने पर stopSelf();
    return START_NOT_STICKY;
  }

  private void createChannelIfNeeded() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      NotificationChannel ch = new NotificationChannel(
          CHANNEL_ID, "Background Tasks", NotificationManager.IMPORTANCE_LOW);
      NotificationManager nm = getSystemService(NotificationManager.class);
      nm.createNotificationChannel(ch);
    }
  }

  @Override
  public IBinder onBind(Intent intent) { return null; }

  @Override
  public void onDestroy() {
    super.onDestroy();
    // cleanup
  }
}
कब उपयोग करें? जब काम user-visible/ongoing हो—जैसे मीडिया प्लेबैक, fitness tracking, navigation।

Bound Service (Skeleton) — Client Interaction

package com.example.myserviceapp;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MyBoundService extends Service {

  private final IBinder binder = new LocalBinder();

  public class LocalBinder extends Binder {
    public MyBoundService getService() {
      return MyBoundService.this;
    }
  }

  @Override
  public IBinder onBind(Intent intent) {
    return binder;
  }

  // Client द्वारा कॉल की जाने वाली कोई method:
  public int getProgressValue() {
    // TODO: वास्तविक प्रोग्रेस/स्टेट लौटाएँ
    return 42;
  }
}

Activity से Bind/Unbind

// Activity snippet
private MyBoundService service;
private boolean bound = false;

private final ServiceConnection conn = new ServiceConnection() {
  @Override public void onServiceConnected(ComponentName n, IBinder b) {
    MyBoundService.LocalBinder lb = (MyBoundService.LocalBinder) b;
    service = lb.getService();
    bound = true;
  }
  @Override public void onServiceDisconnected(ComponentName n) { bound = false; }
};

@Override protected void onStart() {
  super.onStart();
  Intent i = new Intent(this, MyBoundService.class);
  bindService(i, conn, BIND_AUTO_CREATE);
}

@Override protected void onStop() {
  super.onStop();
  if (bound) { unbindService(conn); bound = false; }
}

AndroidManifest.xml में Declaration

<application ...>
  <service android:name=".MyService" />
  <service
      android:name=".MyForegroundService"
      android:foregroundServiceType="dataSync|location|mediaPlayback" />
  <service android:name=".MyBoundService" />
</application>

foregroundServiceType अपने use-case के अनुसार चुनें (Android 10+).

Activity से Start/Stop

// Start simple service
startService(new Intent(this, MyService.class));

// Stop simple service
stopService(new Intent(this, MyService.class));

// Start foreground service (API 26+)
ContextCompat.startForegroundService(
  this, new Intent(this, MyForegroundService.class)
);
Permission: कुछ foreground types (जैसे location) के लिए runtime permissions आवश्यक होंगी।

Best Practices & Background Limits

  • Main thread पर heavy काम न करें: Thread/Executor/Coroutine का उपयोग करें।
  • Deferrable/guaranteed tasks के लिए: WorkManager चुनें (retry, constraints, doze-aware)।
  • Foreground Service तभी: जब task user-visible/ongoing हो; उचित Notification ज़रूर दिखाएँ।
  • Doze/App Standby: बैटरी ऑप्टिमाइज़ेशन के कारण background पर limits आ सकती हैं—अनुरूप design करें।
  • Cleanup: काम पूरा होने पर stopSelf() कॉल करें, leaks से बचें।
  • Crash safety: Exceptions handle करें; long work को try/finally में clean करें।
Alternative (Highly Recommended): Periodic/one-time, network-dependent या charging-dependent tasks के लिए WorkManager ज़्यादा reliable है।

FAQs

Q1: Service और Thread में क्या फर्क है?

Service component है (Android lifecycle के साथ), Thread सिर्फ execution path है। Service के अंदर आप Threads चला सकते हैं—पर Service खुद main thread पर चलती है जब तक आप अलग Thread न बनाएँ।

Q2: क्या हर background काम के लिए Foreground Service जरूरी है?

नहीं। केवल user-visible/ongoing tasks के लिए। Deferrable/retry-able tasks में WorkManager बेहतर है।

Q3: Oreo (API 26+) में क्या बदल गया?

Background execution limits आए—सीधे background service start करना restricted है। ऐसे में startForegroundService(...) + त्वरित startForeground() और/या WorkManager प्रयोग करें।

Comments

Popular posts from this blog

Git And GitHub Collaborators and teams

🎯 Retrofit से API Call कैसे करें – Android Studio में (Java के साथ Step-by-Step गाइड)

How to create React JS application