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

Kotlin ব্যবহার করে Android সার্ভিস থেকে নোটিফিকেশন পাঠানো

ওভারভিউ

এই টিউটোরিয়ালে দেখানো হয়েছে কিভাবে একটি Foreground Service তৈরি করে সেটি থেকে নোটিফিকেশন প্রদর্শন করা যায়। ফোরগ্রাউন্ড সার্ভিস ব্যবহারকারীর কাছে দৃশ্যমান একটি নোটিফিকেশন দিয়ে ব্যাকগ্রাউন্ডে কাজ চালিয়ে রাখে।

প্রয়োজনীয় ধাপসমূহ

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

ধাপ ২: 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"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">
    
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Notification message"
        android:layout_marginBottom="16dp" />
    
    <Button
        android:id="@+id/btnStart"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Service"
        android:layout_marginBottom="8dp" />
    
    <Button
        android:id="@+id/btnStop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Service" />
</LinearLayout>

ধাপ ৩: MainActivity.kt

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {
    private lateinit var editText: EditText
    private lateinit var btnStart: Button
    private lateinit var btnStop: Button
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "Foreground Service Demo"
        
        editText = findViewById(R.id.editText)
        btnStart = findViewById(R.id.btnStart)
        btnStop = findViewById(R.id.btnStop)
        
        btnStart.setOnClickListener {
            val input = editText.text.toString()
            if (input.isNotBlank()) {
                val serviceIntent = Intent(this, ExampleService::class.java).apply {
                    putExtra("inputExtra", input)
                }
                // Android 8.0+ (API 26+) ফোরগ্রাউন্ড সার্ভিস স্টার্ট
                ContextCompat.startForegroundService(this, serviceIntent)
            }
        }
        
        btnStop.setOnClickListener {
            val serviceIntent = Intent(this, ExampleService::class.java)
            stopService(serviceIntent)
        }
    }
}

ধাপ ৪: ExampleService.kt (Foreground Service)

import android.app.*
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.IBinder
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat

class ExampleService : Service() {
    
    private val CHANNEL_ID = "ForegroundServiceChannel"
    private val NOTIFICATION_ID = 1
    
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
    }
    
    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel() {
        val channel = NotificationChannel(
            CHANNEL_ID,
            "Foreground Service Channel",
            NotificationManager.IMPORTANCE_LOW // নয়জ না করে শুধু আইকন
        ).apply {
            description = "Shows foreground service status"
            enableVibration(false)
            setSound(null, null)
        }
        
        val manager = getSystemService(NotificationManager::class.java)
        manager.createNotificationChannel(channel)
    }
    
    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        val input = intent.getStringExtra("inputExtra") ?: "Service Running"
        
        // নোটিফিকেশন বিল্ড
        val notificationIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this, 0, notificationIntent, 
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
        
        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Example Service")
            .setContentText(input)
            .setSmallIcon(R.drawable.ic_notification) // আপনার আইকন ব্যবহার করুন
            .setContentIntent(pendingIntent)
            .setOngoing(true) // স্লাইড করে ডিসমিস করা যাবে না
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .build()
        
        // ফোরগ্রাউন্ড সার্ভিস হিসেবে শুরু
        startForeground(NOTIFICATION_ID, notification)
        
        // এখানে আপনার ব্যাকগ্রাউন্ড কাজ করুন (ডাউনলোড, সিঙ্ক, লোকেশন ট্র্যাকিং ইত্যাদি)
        // কাজ শেষ হলে stopSelf() কল করুন
        
        return START_NOT_STICKY // সিস্টেম কিল করলে রিস্টার্ট করবে না
    }
    
    override fun onBind(intent: Intent?): IBinder? = null
    
    override fun onDestroy() {
        super.onDestroy()
        // নোটিফিকেশন সরাতে চাইলে:
        // NotificationManagerCompat.from(this).cancel(NOTIFICATION_ID)
    }
}

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

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.foregroundservice">
    
    <!-- Android 9 (API 28) এবং নিচে -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    
    <!-- Android 14 (API 34)+ এর জন্য টাইপ স্পেসিফিক পারমিশন -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
    <!-- বা অন্যান্য টাইপ: MEDIA_PLAYBACK, LOCATION, CAMERA, MICROPHONE, HEALTH ইত্যাদি -->
    
    <application ...>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <service
            android:name=".ExampleService"
            android:exported="false"
            android:foregroundServiceType="dataSync" /> <!-- API 34+ জন্য টাইপ বাধ্যতামূলক -->
        
    </application>
</manifest>

🔔 নোটিফিকেশন চ্যানেল (Android 8.0+ / API 26+)

নোটিফিকেশন দেখানোর জন্য চ্যানেল বানানো **বাধ্যতামূলক**। `IMPORTANCE_LOW` বা `MIN` ব্যবহার করলে শব্দ/ভাইব্রেশন ছাড়া শুধু স্ট্যাসবার-এ আইকন দেখাবে।

Android 14+ (API 34) পরিবর্তন: Foreground Service Types

Android 14 থেকে ফোরগ্রাউন্ড সার্ভিস ডিক্লেয়ার করার সময় android:foregroundServiceType অ্যাট্রিবিউট **বাধ্যতামূলক**। উপলব্ধ টাইপগুলো:

  • dataSync - ডেটা সিঙ্ক (ডিফল্ট)
  • mediaPlayback - মিডিয়া প্লেব্যাক
  • location - লোকেশন ট্র্যাকিং
  • camera / microphone - ক্যামেরা/মাইক্রোফোন অ্যাক্সেস
  • health - হেলথ/ফিটনেস ডেটা
  • phoneCall - ফোন কল
  • remoteMessaging - রিমোট মেসেজিং
  • shortService - ছোট সময়ের টাস্ক (< 3 মিনিট)
  • specialUse - স্পেশ্যাল ইউজ কেস
  • systemExempted - সিস্টেম ছাড়

সেরা অনুশীলন

  1. WorkManager ব্যবহার করুন যদি কাজটি ডিফারেবল হয় (সিস্টেম অপ্টিমাইজ করে)
  2. Notification Channel প্রি-ক্রিয়েট করুন (Application ক্লাসে)
  3. PendingIntent.FLAG_IMMUTABLE ব্যবহার করুন (API 23+)
  4. নোটিফিকেশনে Action বাটন যোগ করুন (Pause, Cancel ইত্যাদি)
  5. ব্যাটারি অপ্টিমাইজেশন: setForegroundServiceBehavior() (API 34+)

WorkManager বিকল্প (সুপারিশ করা)

// Worker ক্লাস
class DownloadWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) {
    override suspend fun doWork(): Result {
        val notification = buildNotification()
        setForegroundAsync(foregroundInfo) // ForegroundInfoCompat
        // কাজ করুন
        return Result.success()
    }
}

// এনকিউ
val request = OneTimeWorkRequestBuilder().build()
WorkManager.getInstance(context).enqueue(request)
  1. অ্যান্ড্রয়েড নোটিফিকেশনে InboxStyle স্টাইলিং কীভাবে করবেন?

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

  3. অ্যান্ড্রয়েডে AlarmManager ব্যবহার করে সার্ভিস শুরু করার পদ্ধতি

  4. JavaMail API ব্যবহার করে Android-এ ইমেইল পাঠানো