Foreground Service with Notification chennal



Example code for notification in foreground service

Here we are starting the foreground service from the MainActivity.kt

        //Start foreground service using notification channel id
        button.setOnClickListener {
            val intent = Intent(this, ForeGrService::class.java)
            intent.putExtra("extraText", editText.text.toString())
//            startService(intent) //or
            ContextCompat.startForegroundService(this, intent)
        }

Stop the service from the Activity class

        btn_stop.setOnClickListener {
            val intent: Intent = Intent(this, ForeGrService::class.java)
            stopService(intent)
        }


onStartComment override method will trigger the notification using channel id in ForegroundService class



    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        val extraText = intent?.getStringExtra("extraText");

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val intent = Intent(this, MainActivity::class.java)
            val pendingIntent:PendingIntent = PendingIntent.getActivity(this, 1,intent, 0)

            val notification: Notification = Notification.Builder(this, CHENNEL_2_ID)
                .setContentText("Service text $extraText")
                .setContentTitle("Service title")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setLargeIcon(
                    BitmapFactory.decodeResource(
                        this.resources,
                        R.drawable.ic_launcher_background
                    )
                )
                .setContentIntent(pendingIntent)
                .build()

            startForeground(1, notification)
        }

//        stopSelf()

        return START_STICKY;

    }


You can get full source code from the GitHub link

https://github.com/AndroidManikandan5689/Notification-in-Foreground-Service-Android

Comments

Popular posts from this blog

Your build is currently configured to use incompatible Java 21.0.3 and Gradle 8.2.1. Cannot sync the project.

Google Assistant Implementation in Android application with app actions