Android Notification Load Image from Url Using Glide In Java

 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/2021/02/android-notification-java-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'
    annotationProcessor '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 androidx.annotation.NonNull;

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
public class AppNameGlideModule extends AppGlideModule {


    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        super.applyOptions(context, builder);

        RequestOptions requestOptions = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL)
                .signature(new 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 .
String imageUrl = "https://raw.githubusercontent.com/TutorialsBuzz/cdn/main/android.jpg";

GlideApp.with(getApplicationContext())
	.asBitmap()
	.load(imageUrl)
	.into(new CustomTarget<Bitmap>() {
		@Override
		public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
			//largeIcon
			notificationBuilder.setLargeIcon(resource);
			//Big Picture
			notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(resource));

			Notification notification = notificationBuilder.build();
			notificationManager.notify(NotificationID.getID(), notification);
		}

		@Override
		public void onLoadCleared(@Nullable Drawable placeholder) {
		}
	}); 


1. MainActivity


Main activity complete code

file : MainActivity.java
package com.tutorialsbuzz.notificationimgload;

import android.app.Notification;
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.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
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;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button notifyBtn = findViewById(R.id.notifyBtn);

        notifyBtn.setOnClickListener(v -> {

            createNotification(
                    getResources().getString(R.string.notification_title),
                    getResources().getString(R.string.notification_content),
                    getResources().getString(R.string.notification_channel)
            );

        });

    }

    /**
     * Create Notification
     * Param
     * 1. title
     * 2. content
     * 3. channelId
     * 4.priorty
     * 5. notificationId
     */

    private void createNotification(String title, String content,
                                    String channedId) {


        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(getApplicationContext(), channedId)
                        .setSmallIcon(R.drawable.ic_notifications_active)
                        .setAutoCancel(true)
                        .setLights(Color.BLUE, 500, 500)
                        .setVibrate(new long[]{500, 500, 500})
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setContentTitle(title)
                        .setContentText(content)
                        .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);


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

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

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

        GlideApp.with(getApplicationContext())
                .asBitmap()
                .load(imageUrl)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        //largeIcon
                        notificationBuilder.setLargeIcon(resource);
                        //Big Picture
                        notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(resource));

                        Notification notification = notificationBuilder.build();
                        notificationManager.notify(NotificationID.getID(), notification);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                    }
                });
    }

    static class NotificationID {
        private final static AtomicInteger c = new AtomicInteger(100);

        public static int getID() {
            return c.incrementAndGet();
        }
    }

}





No comments:

Post a Comment