Load Image from Url in Notification Android

Load image from url in notification Android

Changed my code as below and its working now :

private class sendNotification extends AsyncTask<String, Void, Bitmap> {

Context ctx;
String message;

public sendNotification(Context context) {
super();
this.ctx = context;
}

@Override
protected Bitmap doInBackground(String... params) {

InputStream in;
message = params[0] + params[1];
try {

URL url = new URL(params[2]);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
in = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(in);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Bitmap result) {

super.onPostExecute(result);
try {
NotificationManager notificationManager = (NotificationManager) ctx
.getSystemService(Context.NOTIFICATION_SERVICE);

Intent intent = new Intent(ctx, NotificationsActivity.class);
intent.putExtra("isFromBadge", false);

Notification notification = new Notification.Builder(ctx)
.setContentTitle(
ctx.getResources().getString(R.string.app_name))
.setContentText(message)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(result).build();

// hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;

notificationManager.notify(1, notification);

} catch (Exception e) {
e.printStackTrace();
}
}
}

How to use an image URL as the image for notifications instead of images from the drawable?

Sample ImageYou can try this:

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.Glide
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(
"Hey Hello!!",
"How are you?",
resources.getString(R.string.notification_channel)
)
}
}

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://i.pinimg.com/originals/1b/7e/4e/1b7e4eac8558ad54d6fe94ed4e14cb84.jpg"
Glide.with(applicationContext)
.asBitmap()
.load(imageUrl)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
notificationBuilder.setLargeIcon(resource) //largeIcon
notificationBuilder.setStyle(
NotificationCompat.BigPictureStyle().bigPicture(resource)
) //Big Picture
val notification = notificationBuilder.build()
notificationManager.notify(NotificationID.iD, notification)
}

override fun onLoadCleared(placeholder: Drawable?) {}
override fun onLoadFailed(errorDrawable: Drawable?) {
super.onLoadFailed(errorDrawable)
}
})
}

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

How can I show an image from link in android push notification?

try this, will work

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this);

Bitmap bitmap = getBitmapFromURL(url);

NotificationCompat.BigPictureStyle s = new NotificationCompat.BigPictureStyle().bigPicture(bitmap);
s.setSummaryText("Image");
nBuilder.setStyle(s);
nBuilder.setSmallIcon(R.mipmap.ic_launcher);

Create Method getBitmapFromURL

public Bitmap getBitmapFromURL(String strURL) {
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

mNotificationManager.notify(0, nBuilder.build());

how can use url image to notification LargeIcon in Android?

BitmapFactory.decodeFile() works for decoding local files only. When you're dealing with a remote address you should download the image using an image loading library like Glide and pass the decoded bitmap to notification builder object. Here is a simple example to download image as bitmap using a blocking method:

private Bitmap getLargeIcon(Context context, String picturePath) {
if (picturePath != null) {
try {
return Glide.with(context)
.as(Bitmap.class)
.load(picturePath)
.get(4000, TimeUnit.MILLISECONDS);
} catch (ExecutionException | InterruptedException | TimeoutException ignored) {}
}
return null;
}

And call the method in your notification function:

Bitmap largeIcon = getLargeIcon(this, bigPhoto);

Note: Since getLargeIcon uses a blocking method to download your image, don't forget to call your sendNotification function on a worker thread.

How can I add picture to notification large icon with Picasso having only URL of this picture?

public class EpisodeNotifyActivity extends AppCompatActivity {

private NotificationManagerCompat notificationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ativity_episode_notify);

final Timetable timetable = (Timetable) requestService.getResult();
ImageView serImage = (ImageView) findViewById(R.id.seriesImage1);

Button button = findViewById(R.id.notify);
Picasso.get()
.load(timetable.getImage())
.into(serImage);

NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, EpisodeNotifyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
@SuppressLint("WrongConstant")
NotificationChannel notificationChannel = new NotificationChannel("my_notification", "n_channel", NotificationManager.IMPORTANCE_MAX);
notificationChannel.setDescription("description");
notificationChannel.setName("Channel Name");
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);

final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_live_tv_black_24dp)
.setContentTitle(timetable.getSeriesName().toUpperCase() + ", New Episode")
.setContentText(timetable.getEpisodesSeason().toString() + "x" + timetable.getEpisodesNumber() + " " + timetable.getEpisodeName())
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setOnlyAlertOnce(true)
.setChannelId("my_notification")
.setColor(Color.parseColor("#3F5996"));

Picasso.get().load(timetable.getImage())
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

// !!!!!!!! MAGIC HAPPENS HERE
notificationBuilder.setLargeIcon(bitmap);
}

@Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
}

@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {

}
});

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendNotification();
}
});

}
}

private void sendNotification() {
assert notificationManager != null;
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(m, notificationBuilder.build());
}
}


Related Topics



Leave a reply



Submit