Skip to content

Instantly share code, notes, and snippets.

@alokomkar
Created November 2, 2022 14:22
Show Gist options
  • Save alokomkar/2e03c84f9d9a671f033469e080a91497 to your computer and use it in GitHub Desktop.
Save alokomkar/2e03c84f9d9a671f033469e080a91497 to your computer and use it in GitHub Desktop.
Step 4 : Foreground service : NotificationHelper
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import com.alokomkar.activity.HomeActivity
import com.alokomkar.javacollections.R
class NotificationHelper(private val context: Context) {
private val notificationBuilder: NotificationCompat.Builder by lazy {
NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(context.getString(R.string.notification_title))
.setContentText(context.getString(R.string.notification_message))
.setTicker(context.getString(R.string.ticker_text))
.setSound(null)
.setContentIntent(contentIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
}
private val notificationManager by lazy {
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
}
private val contentIntent by lazy {
PendingIntent.getActivity(
context,
0,
Intent(context, HomeActivity::class.java),
PendingIntent.FLAG_IMMUTABLE
)
}
fun getNotification(): Notification {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannel(createChannel())
}
return notificationBuilder.build()
}
fun updateNotification(notificationText: String? = null) {
notificationText?.let { notificationBuilder.setContentText(it) }
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build())
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createChannel() =
NotificationChannel(
CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = CHANNEL_DESCRIPTION
setSound(null, null)
}
companion object {
const val NOTIFICATION_ID = 232
private const val CHANNEL_ID = "Audio_Playback_Channel"
private const val CHANNEL_NAME = "Audio_Playback"
private const val CHANNEL_DESCRIPTION = "Audio_Playback_Description"
}
}
enum class ServiceAction(val value: String) {
START_ACTION("start"),
STOP_ACTION("stop")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment