কম্পিউটার টিউটোরিয়াল

অ্যান্ড্রয়েডে ব্যাকগ্রাউন্ড সার্ভিস সবসময় চালানোর পদ্ধতি

স্টিকি সার্ভিস তৈরি করে ব্যাকগ্রাউন্ডে চলাকালীন এক্সিকিউশন

এই উদাহরণটি দেখায় কীভাবে `START_STICKY` এবং `onTaskRemoved()` ব্যবহার করে একটি সার্ভিসকে সবসময় ব্যাকগ্রাউন্ডে চালিয়ে রাখা যায়। দ্রষ্টব্য: Android 8.0 (Oreo) থেকে ব্যাকগ্রাউন্ড এক্সিকিউশন লিমিটস আরো কঠোর হয়েছে।

ধাপ ১: নতুন প্রজেক্ট তৈরি করুন

Android Studio-তে File → New Project থেকে প্রজেক্ট তৈরি করুন।

ধাপ ২: লেআউট XML (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
    <Button
        android:id="@+id/button"
        android:text="Click here to start background Service"
        android:textStyle="bold"
        android:textSize="16sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
</RelativeLayout>

ধাপ ৩: সার্ভিস ক্লাস তৈরি করুন (MyService.java)

Right-click on package → New → Service → Service সিলেক্ট করুন।

package app.com.sample;

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

public class MyService extends Service {
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(getApplicationContext(), "Service running in Background", Toast.LENGTH_SHORT).show();
        
        // আপনার ব্যাকগ্রাউন্ড কাজ এখানে করুন
        // উদাহরণ: লোকেশন ট্র্যাকিং, মিউজিক প্লে, সিন্ক ইত্যাদি
        
        return START_STICKY; // সিস্টেম কিল করলে রিস্টার্ট করবে
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null; // বাইন্ডেড সার্ভিস না হলে null রিটার্ন করুন
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        // অ্যাপ টাস্ক ম্যানেজার থেকে বন্ধ করলে সার্ভিস রিস্টার্ট
        Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
        restartServiceIntent.setPackage(getPackageName());
        startService(restartServiceIntent);
        super.onTaskRemoved(rootIntent);
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        // ক্লিনআপ কাজ করুন
    }
}

ধাপ ৪: MainActivity.java বাস্তবায়ন

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService(new Intent(getApplicationContext(), MyService.class));
            }
        });
    }
}

গুরুত্বপূর্ণ: Android 8.0+ (Oreo) সীমাবদ্ধতা

Android 8.0 থেকে ব্যাকগ্রাউন্ড সার্ভিসে কঠোর সীমাবদ্ধতা রয়েছে:

  • অ্যাপ ব্যাকগ্রাউন্ডে থাকলে সার্ভিস কিছু মিনিটের পর বন্ধ হয়ে যায়
  • Foreground Service ব্যবহার করুন (নোটিফিকেশন সহ) চলাকালীন এক্সিকিউশনের জন্য
  • startForegroundService() এবং সার্ভিসে startForeground() কল করুন

Foreground Service উদাহরণ (Android 8.0+ এর জন্য)

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // নোটিফিকেশন তৈরি করুন
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setContentTitle("Background Service")
        .setContentText("Running...")
        .setSmallIcon(R.drawable.ic_notification)
        .build();
    
    // ফোরগ্রাউন্ড সার্ভিস হিসেবে শুরু করুন
    startForeground(1, notification);
    
    return START_STICKY;
}

// onCreate-এ নোটিফিকেশন চ্যানেল তৈরি করুন (API 26+)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(
        CHANNEL_ID, "Background Service", NotificationManager.IMPORTANCE_LOW);
    NotificationManager manager = getSystemService(NotificationManager.class);
    manager.createNotificationChannel(channel);
}

ধাপ ৫: AndroidManifest.xml (সার্ভিস ডিক্লেয়ারেশন সহ)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    
    <!-- ফোরগ্রাউন্ড সার্ভিসের জন্য (API 28+) -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    
    <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">
        
        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="false"
            android:foregroundServiceType="location|mediaPlayback|dataSync" />
        
        <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>

আধুনিক বিকল্প: WorkManager

পিরিয়ডিক বা ডিফারেবল ব্যাকগ্রাউন্ড কাজের জন্য Google-এর **WorkManager** ব্যবহার করা সেরা প্র্যাকটিস:

// build.gradle
implementation "androidx.work:work-runtime:2.9.0"

// Worker ক্লাস
public class MyWorker extends Worker {
    public MyWorker(@NonNull Context context, @NonNull WorkerParameters params) {
        super(context, params);
    }
    
    @NonNull
    @Override
    public Result doWork() {
        // ব্যাকগ্রাউন্ড কাজ করুন
        return Result.success();
    }
}

// শিডিউল করুন
PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(MyWorker.class, 15, TimeUnit.MINUTES)
    .build();
WorkManager.getInstance(context).enqueue(workRequest);

অ্যাপ্লিকেশন টেস্ট করুন

অ্যাপ রান করুন, বাটনে ক্লিক করলে সার্ভিস শুরু হবে। রিসেন্ট অ্যাপস থেকে অ্যাপ বন্ধ করলেও সার্ভিস রিস্টার্ট হবে (Android 7.0 নিচে)। Android 8.0+ এ Foreground Service ব্যবহার করুন।

  1. Android-এ নোটিফিকেশন থেকে সার্ভিস শুরু করার পদ্ধতি

  2. Android-এ বুট টাইমে সার্ভিস শুরু করার পদ্ধতি

  3. অ্যান্ড্রয়েড ডিভাইসে লিনাক্স চালানোর পদ্ধতি

  4. উইন্ডোজ ১১-এ WSA সবসময় ব্যাকগ্রাউন্ডে রান করার পদ্ধতি