If the content you are planning to present to the end user is short, then, instead of dialogs, you should try notifications. We can customize notifications in many different ways. Here, we will present some basic customizations. Creating and displaying notifications is easy. It requires more knowledge of Android than we have learned so far. Don't worry; we will do our best to explain it. You will face many of these classes in the later chapters.
We will demonstrate how to use notifications as follows:
- Define a notificationBuilder and pass a small icon, content title, and content text as follows:
val notificationBuilder = NotificationCompat.Builder(context) .setSmallIcon(R.drawable.icon) .setContentTitle("Hello!") .setContentText("We love Android!")
- Define Intent for activity of your application. (More about intents, will be discussed in the next chapter):
val result = Intent(context, MyActivity::class.java)
- Now define the stack builder object that will contain the back stack for the activity as follows:
val builder = TaskStackBuilder.create(context)
- Add back stack for the intent:
builder.addParentStack(MyActivity::class.java)
- Add intent at the top of the stack:
builder.addNextIntent(result) val resultPendingIntent = builder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT )Define ID for the
notification and notify:
val id = 0 notificationBuilder.setContentIntent(resultPendingIntent) val manager = getSystemService(NOTIFICATION_SERVICE) as
NotificationManager manager.notify(id, notificationBuilder.build())