Skip to content

Instantly share code, notes, and snippets.

@ahmed-shehataa
Created October 1, 2020 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmed-shehataa/4cf8fb5a945bb9613cffce1b49b122cf to your computer and use it in GitHub Desktop.
Save ahmed-shehataa/4cf8fb5a945bb9613cffce1b49b122cf to your computer and use it in GitHub Desktop.
// How to use it
// just call this
NotificationHelper.Builder(requireContext())
.setTitle("Hello")
.setDescription("Tourism is travel for pleasure or business; also the theory and practice")
.build()
class NotificationHelper private constructor(builder: Builder) {
init {
notify(builder.context, builder.title, builder.description)
}
companion object {
const val CHANNEL_ID = "1"
}
private fun notify(context: Context, textTitle: String, textContent: String) {
// Create an explicit intent for an Activity in your app
val intent = Intent(context, SplashActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
createNotificationChannel(context)
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_logo_icon)
.setContentTitle(textTitle)
.setContentText(textContent)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setStyle(NotificationCompat.BigTextStyle())
with(NotificationManagerCompat.from(context)) {
// notificationId is a unique int for each notification that you must define
notify(1, builder.build())
}
}
private fun createNotificationChannel(context: Context) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = context.getString(R.string.channel_name)
val descriptionText = context.getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
class Builder(val context: Context) {
var title: String = "Alfateha title"
private set
var description: String = "Alfateha description"
private set
fun setTitle(title: String): Builder {
this.title = title
return this
}
fun setDescription(description: String): Builder {
this.description = description
return this
}
fun build() {
NotificationHelper(this)
}
}
}
@ahmed-shehataa
Copy link
Author

NotificationHelper is a class is build with builder design pattern to push a noti to the use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment