Notifications in Kotlin

Notification is a message that is used to display some short messages outside of our main application. Even if the app is not running, notifications will still work. Notifications have the following contents: an icon, title of notification and some text content.

In this article we will be discussing how to produce notifications in Kotlin .

Let’s start by first creating a project in Android Studio. To do so, follow these instructions:



  • Click on File, then New and then New Project and give name whatever you like
  • Then, select Kotlin language Support and click next button
  • Select minimum SDK, whatever you need.
  • Select Empty activity and then click finish.

Modify activity_main.xml file

Second step is to design our layout page. Here, we will use the RelativeLayout to get the Scroll View from the Kotlin file.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
  
    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:id="@+id/btn"
            android:text="Send Notification"
    />
  
</RelativeLayout>

chevron_right


Create a new activity named afterNotification. For this go to res/layout then right click and select new then activity, Empty Activity.When someone click on the notification, this activity will open up in our app that is the user will be redirected to this page.

Modify activity_after_notification.xml file

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".afterNotification">
      
    <TextView 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:text="Welcome To GeeksforGeeks"
            android:id="@+id/textView"
            android:layout_centerInParent="true"
            android:textSize="15sp"
            android:textStyle="bold"/>
  
</RelativeLayout>

chevron_right


Note: Without configuring Notification Channels, you cannot build notification for applications with Android API >=26. For them generating a notification channel is mandatory. Apps with API<26 doesn't need notification channel they just need notification builder.Each channel is supposed to have a particular behavior which will be applicable to all the notifications which are a part of it.

Every channel will therefore have a Channel ID which basically will act as a unique identifier for this Channel which will be useful if user wants to differentiate a particular notification channel. In contrast, Notification builder provides a convenient way to set the various fields of a Notification and generate content views using the platform's notification layout template but is not able to target a particular notification channel.

Modify MainActivity.kt file

Open app/src/main/java/yourPackageName/MainActivity.kt. In this file, paste the following:

filter_none

edit
close

play_arrow

link
brightness_4
code

package i.apps.notifications
import androidx.appcompat.app.AppCompatActivity
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.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import android.os.Bundle
  
import android.widget.Button
import android.widget.RemoteViews
  
class MainActivity : AppCompatActivity() {
  
    //declaring variables
    lateinit var notificationManager : NotificationManager
    lateinit var notificationChannel : NotificationChannel
    lateinit var builder : Notification.Builder
    private val channelId = "i.apps.notifications"
    private val description = "Test notification"
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        //accessing button
        val btn = findViewById<Button>(R.id.btn)
  
        //it is a class to notify the user of events that happen. 
        // This is how you tell the user that something has happened in the
        background.notificationManager = 
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
  
        //onClick listener for the button
        btn.setOnClickListener {
  
            //pendingIntent is an intent for future use i.e after
            // the notification is clicked, this intent will come into action
  
            val intent = Intent(this,afterNotification::class.java)
  
            //FLAG_UPDATE_CURRENT specifies that if a previous 
            // PendingIntent already exists, then the current one 
            // will update it with the
            latest intent
            // 0 is the request code, using it later with the 
            // same method again will get back the same pending 
            // intent for future reference
            //intent passed here is to our afterNotification class
  
            val pendingIntent = PendingIntent.getActivity(this,
                0,intent,PendingIntent.FLAG_UPDATE_CURRENT)
  
            //RemoteViews are used to use the content of 
            // some different layout apart from the current activity layout
  
            val contentView = RemoteViews(packageName,
                R.layout.activity_after_notification)
  
            //checking if android version is greater than oreo(API 26) or not
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                notificationChannel = NotificationChannel(
                    channelId,description,NotificationManager.IMPORTANCE_HIGH)
                notificationChannel.enableLights(true)
                notificationChannel.lightColor = Color.GREEN
                notificationChannel.enableVibration(false)
                notificationManager.createNotificationChannel(notificationChannel)
  
                builder = Notification.Builder(this,channelId)
                    .setContent(contentView)
                    .setSmallIcon(R.drawable.ic_launcher_background)
                    .setLargeIcon(BitmapFactory.decodeResource(this.resources,
                        R.drawable.ic_launcher_background))
                    .setContentIntent(pendingIntent)
            }else{
  
                builder = Notification.Builder(this)
                    .setContent(contentView)
                    .setSmallIcon(R.drawable.ic_launcher_background)
                    .setLargeIcon(BitmapFactory.decodeResource(this.resources,
                        R.drawable.ic_launcher_background))
                    .setContentIntent(pendingIntent)
            }
            notificationManager.notify(1234,builder.build())
        }
  
    }
  
  
}

chevron_right


AndroidManifest.xml file

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
          package="i.apps.notifications">
  
    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".afterNotification">
        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
  
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
  
</manifest>

chevron_right


Run as Emulator:





My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.