Android Custom Notification Template Kotlin

In the previous tutorial we have seen android basic notification example  and learned about notification anatomy , notification channel , notification importance , lock screen notification , playing notification sound and setting pending intent to notification .

In this tutorial we will see how to create your template (custom layout) for notification 

Create Custom Layout for notification


1. Big Layout

file : large_notification_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingStart="16dp"
    android:paddingEnd="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="18dp"
            android:layout_height="18dp"
            android:layout_gravity="center_vertical"
            android:src="@mipmap/ic_launcher" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginStart="6dp"
            android:layout_marginLeft="6dp"
            android:ellipsize="end"
            android:maxLines="2"
            android:text="@string/app_name"
            android:textColor="#297A9B"
            android:textSize="12dp" />

    </LinearLayout>

    <TextView
        android:id="@+id/notification_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="10dp"
        android:ellipsize="end"
        android:maxLines="2"
        android:textSize="14dp" />

    <ImageView
        android:id="@+id/notification_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"
        android:scaleType="fitXY" />
</LinearLayout>




2. Small Layout 

file : small_layout_notification.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingStart="16dp"
    android:paddingTop="3dp"
    android:paddingEnd="16dp"
    android:paddingBottom="3dp">

    <ImageView
        android:id="@+id/notification_image"
        android:layout_width="70dp"
        android:layout_height="60dp"
        android:layout_marginStart="3dp"
        android:layout_marginEnd="10dp"
        android:scaleType="fitXY"
        android:layout_marginLeft="3dp"
        android:layout_marginRight="10dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:layout_width="18dp"
                android:layout_height="18dp"
                android:layout_gravity="center_vertical"
                android:src="@mipmap/ic_launcher" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginStart="6dp"
                android:ellipsize="end"
                android:maxLines="2"
                android:text="@string/app_name"
                android:textColor="#297A9B"
                android:textSize="12dp" />

        </LinearLayout>

        <TextView
            android:id="@+id/notification_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:ellipsize="end"
            android:maxLines="2"
            android:textColor="#297A9B"
            android:textSize="14dp" />

    </LinearLayout>
</LinearLayout>

    

RemoteView


A class that describes a view hierarchy that can be displayed in another process. The hierarchy is inflated from a layout resource file, and this class provides some basic operations for modifying the content of the inflated hierarchy.

Creating RemoteViews and Setting to Notification

 val builder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_notifications_active)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true)
            .setVibrate(longArrayOf(500, 500, 500))


1 Create RemoteViews 
val smallContent = RemoteViews(getPackageName(), R.layout.small_layout_notification)
val bigContent = RemoteViews(getPackageName(), R.layout.large_notification_layout)

2. Setting Text In RemoteView  
bigContent.setTextViewText(R.id.notification_title, "Notification Custom Text")
smallContent.setTextViewText(R.id.notification_title, "Notification Custom Text")

3. Setting Image In RemoteView content
bigContent.setImageViewResource(R.id.notification_image, R.mipmap.ic_launcher)
smallContent.setImageViewResource(R.id.notification_image, R.mipmap.ic_launcher)

4. Setting RemoteView to notification 
builder.setContent(smallContent)
builder.setCustomBigContentView(bigContent)   

XML Layout


Create xml layout one for MainActivity and another for NotifyActivity  
1. file : activity_main.xml   
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Custom Notification"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

2. file : activity_notify.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ProgressBar
        android:id="@+id/progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:indeterminate="true" />

</RelativeLayout>


Activities



file : MainActivity.kt 
package com.tutorialsbuzz.androidcustomnotification

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.widget.RemoteViews
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button1.setOnClickListener({
            createCustomNotification()
        })

    }

    private fun createCustomNotification() {

        val notificationID: Int = 100
        // Create an explicit intent for an Activity in your app
        val intent = Intent(this, NotifyActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        intent.data = Uri.parse("https://www.tutorialsbuzz.com/")

        val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)

        val channelId = "News"
        val channelName = "News"

        val builder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_notifications_active)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true)
            .setVibrate(longArrayOf(500, 500, 500))

        val smallContent = RemoteViews(getPackageName(), R.layout.small_layout_notification)
        val bigContent = RemoteViews(getPackageName(), R.layout.large_notification_layout)

        bigContent.setTextViewText(R.id.notification_title, "Notification Custom Text")
        smallContent.setTextViewText(R.id.notification_title, "Notification Custom Text")

        bigContent.setImageViewResource(R.id.notification_image, R.mipmap.ic_launcher)
        smallContent.setImageViewResource(R.id.notification_image, R.mipmap.ic_launcher)

        builder.setContent(smallContent)
        builder.setCustomBigContentView(bigContent)

        with(NotificationManagerCompat.from(this)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel(
                    channelId,
                    channelName,
                    NotificationManager.IMPORTANCE_HIGH
                )
                createNotificationChannel(channel)
                notify(notificationID, builder.build())
            }
        }
    }

}

file : NotificationActivity.kt 
package com.tutorialsbuzz.androidcustomnotification

import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_notify.*

class NotifyActivity : AppCompatActivity() {

    companion object {
        const val notify_title: String = "notify_title"
        const val notify_content: String = "notify_content"

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_notify)

        webview.settings.javaScriptEnabled = true
        webview.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                progress.visibility = View.VISIBLE
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                progress.visibility = View.GONE
            }

            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                return false
            }
        };

        loadNotificationPage(intent)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        loadNotificationPage(intent)
    }

    private fun loadNotificationPage(intent: Intent?): Unit {
        webview.loadUrl(intent?.dataString);
    }


}



No comments:

Post a Comment