Android Notification Load Image from Url Using Glide In Kotlin

 A Notification is a message that Android displays outside your app's UI to provide the user with reminders , In the previous tutorial we have seen notification anatomy how to create notification with title content and image , If you have requirement where you have to load image which is hosted in remote CDN into notification , In such case we will make request to fetch image and load ,to make it more easy and clean code we will glide library 

To Know more about creating notification with title content and channel please have a look at  https://www.tutorialsbuzz.com/2020/08/android-notification-koltin-example.html

1. Add Glide Dependency to build.gradle(app-level)


Add Glide dependency to build.gradle(app-level) 

file : build.gradle
dependencies {
    ...............
	...............
    implementation 'com.github.bumptech.glide:glide:4.11.0'
    kapt 'com.github.bumptech.glide:compiler:4.11.0'
}

1. Android Manifest


1. Add Internet Permission to Android Manifest .

2. Add usesCleartextTraffic flag to manifest application tag , required for glide library  ( Android N offers finer-grained control over cleartext traffic policy. As opposed to android:usesCleartextTraffic attribute which applies to all destinations with which an app communicates .)

file : AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorialsbuzz.notificationimgload">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/Theme.NotificationImgLoad">
        <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>


2. XML Layout


Create XML Layout inside res/layout/ and add button .

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/notifyBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Notify"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>


1. Create App Glide Module


Create app glide module by "AppNameGlideModule" by extending AppGlideModule 

file : AppNameGlideModule.java
package com.tutorialsbuzz.notificationimgload

import android.content.Context
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.module.AppGlideModule
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.signature.ObjectKey

@GlideModule
class AppNameGlideModule : AppGlideModule() {
    override fun applyOptions(context: Context, builder: GlideBuilder) {
        super.applyOptions(context, builder)
        val requestOptions = RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL)
            .signature(
                ObjectKey(
                    System.currentTimeMillis() / (24 * 60 * 60 * 1000)
                )
            )
        builder.setDefaultRequestOptions(requestOptions)
    }
}



1. Loading Image Into Notification (setLargeIcon and BigPicture) From Url


We will load image hosted at "https://raw.githubusercontent.com/TutorialsBuzz/cdn/main/android.jpg" into notification largeIcon and bigPicture .

  • Using GlideModule reference we will make request by passing requestUrl .
  • Create a Glide CustomTarget and override the onResourceReady and onLoadCleared 
  • Inside onResourceReady , the onResourceReady method contains bitmap now load this bitmap into your notification and call notify using notificationManager .
  val imageUrl = "https://raw.githubusercontent.com/TutorialsBuzz/cdn/main/android.jpg"
  
  GlideApp.with(applicationContext)
	.asBitmap()
	.load(imageUrl)
	.into(object : CustomTarget<Bitmap>() {
		override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
			//largeIcon
			notificationBuilder.setLargeIcon(resource)
			//Big Picture
			notificationBuilder.setStyle(
				NotificationCompat.BigPictureStyle().bigPicture(resource)
			)
			val notification = notificationBuilder.build()
			notificationManager.notify(NotificationID.iD, notification)
		}

		override fun onLoadCleared(placeholder: Drawable?) {}
	})

1. MainActivity


Main activity complete code

file : MainActivity.java
package com.tutorialsbuzz.notificationimgload

import android.app.NotificationChannel
import android.app.NotificationManager
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import java.util.concurrent.atomic.AtomicInteger


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val notifyBtn = findViewById<Button>(R.id.notifyBtn)
        notifyBtn.setOnClickListener { v: View? ->
            createNotification(
                resources.getString(R.string.notification_title),
                resources.getString(R.string.notification_content),
                resources.getString(R.string.notification_channel),
            )
        }
    }

    /**
     * Create Notification
     * Param
     * 1. title
     * 2. content
     * 3. channelId
     * 4.priorty
     * 5. notificationId
     */
    private fun createNotification(
        title: String, content: String,
        channedId: String
    ) {

        val notificationBuilder = NotificationCompat.Builder(applicationContext, channedId)
            .setSmallIcon(R.drawable.ic_notifications_active)
            .setAutoCancel(true)
            .setLights(Color.BLUE, 500, 500)
            .setVibrate(longArrayOf(500, 500, 500))
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentTitle(title)
            .setContentText(content)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)

        // Since android Oreo notification channel is needed.
        val notificationManager = NotificationManagerCompat.from(this@MainActivity)

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channedId,
                channedId,
                NotificationManager.IMPORTANCE_HIGH
            )
            channel.lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
            notificationManager.createNotificationChannel(channel)
        }

        val imageUrl = "https://raw.githubusercontent.com/TutorialsBuzz/cdn/main/android.jpg"

        GlideApp.with(applicationContext)
            .asBitmap()
            .load(imageUrl)
            .into(object : CustomTarget<Bitmap>() {
                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    notificationBuilder.setLargeIcon(resource)
                    val notification = notificationBuilder.build()
                    notificationManager.notify(NotificationID.iD, notification)
                }

                override fun onLoadCleared(placeholder: Drawable?) {

                }
            })

    }

    internal object NotificationID {
        private val c = AtomicInteger(100)
        val iD: Int
            get() = c.incrementAndGet()
    }
}




1 comment:

Post a Comment