I am currently trying to implement push notifications for my android app with FCM, However when I send a notification it doesn't appear on the phone. I know for sure that the app received the message since it appears in the logcat, but the notification itself doesn't appear and i'm not sure where I went wrong. I got an error from Glide but I tried again without the LargeIcon and the .notify line outside of the glide line and still nothing appeared. Any help is appreciated :)
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Spannable sb = new SpannableString("Switcheroo");
sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.app_icon_waves_round)
.setContentTitle(sb)
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Glide.with(getApplicationContext()).asBitmap().load(image).placeholder(R.drawable.music_placeholder).into(new CustomTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
notificationBuilder.setLargeIcon(resource);
notificationManager.notify(0, notificationBuilder.build());
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
LogCat:
D/PAYLOAD: Message data payload: {image=https://is1-ssl.mzstatic.com/image/thumb/WNUBiv2P6YSklHn9eA5nlg/1000x1000bb.jpeg, message=Barbecu sent you his "Run The Jewels" Playlist}
W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a #GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
Starting from Android 8.0 (API level 26), notifications won't show unless you provide NotificationChannel as a second argument to the NotificationCompat.Builder constructor.
So, to solve that, create a NotificationChannel for API 26+
// Notification channels are only available in OREO and higher.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel
("PRIMARY_CHANNEL_ID",
"Service",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("Description");
notificationManager.createNotificationChannel(notificationChannel);
}
use the channel ID "PRIMARY_CHANNEL_ID" as a second argument to the NotificationCompat.Builder constructor.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "PRIMARY_CHANNEL_ID")
.setSmallIcon(R.mipmap.app_icon_waves_round)
.setContentTitle(sb)
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
when you use Glide4 in your app. you have to make class like this.
import android.content.Context;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
#GlideModule
public final class MyAppGlideModule extends AppGlideModule {
#Override
public void applyOptions(Context context, GlideBuilder builder) {
}
}
check this. happy coding!
Related
I have been trying to create an incoming call type notification for my Android app, written in native Java code, and in many resources online I have read that using the .setOngoing(true) tag on the NotificationBuilder would be enough to have the desired behaviour of the notification being visible, playing the ringtone sound until it is clicked, but that has not worked for me.
I have also tried using the flags Notification.FLAG_INSISTENT and Notification.FLAG_NO_CLEAR without success.
Here is my current code:
private void ringtone(Context context){
String channelId = "call_channel";
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Incoming Call")
.setContentText("You have an incoming call")
.setCategory(Notification.CATEGORY_CALL)
.setOngoing(true)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(contentIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence channelName = "Incoming Calls";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableVibration(true);
long[] pattern = {0, 1000, 500, 1000};
notificationChannel.setVibrationPattern(pattern);
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.setLegacyStreamType(AudioManager.STREAM_RING)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
notificationChannel.setAllowBubbles(true);
}
notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notificationChannel.setSound(ringtoneUri,att);
notificationManager.createNotificationChannel(notificationChannel);
}else{
notificationBuilder.setSound(ringtoneUri);
}
Notification notification = notificationBuilder.build();
notification.flags |= Notification.FLAG_INSISTENT | Notification.FLAG_NO_CLEAR;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
My intention is to have an incoming call type of notification much like other applications such as MS Teams, Whatsapp, ETC. and my issue is that the notification gets minimized after showing on screen for a few seconds, and the ringtone stops shortly after. Thank you for any help with this.
i want to ask about FCM. I have an FCM service that is running as it should this is my code
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "ch1")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
NotificationChannel channel = new NotificationChannel("ch1",
getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
channel.enableLights(true);
channel.enableVibration(true);
mNotificationManager.createNotificationChannel(channel);
}
mNotificationManager.notify(0, notificationBuilder.build());
but i want to disable this notification on spesific activity, for example i have ChatActivity. where if i get notificatin on this activity, the fcm service is not showing a notification. I have tried implement this code but still not work
if(!(this.getApplicationContext() instanceof ChatActivity)){
//build the notification
}
anyone have solution for my problem? thank you.
First of all keep a flag in your SharedPreferences for ChatActivity to know if it's open or not.
Now inside ChatActivity set this flag true in onResume() and false in onStop(). Like this:
#Override
protected void onResume() {
super.onResume();
AppPreferences.getInstance().setBoolean("IS_CHAT_ACTIVITY", true);
}
#Override
protected void onStop() {
super.onStop();
AppPreferences.getInstance().setBoolean("IS_CHAT_ACTIVITY", true);
}
If you don't know anything about SharedPreferences check This Tutorial.
Now in your FCM Service class, you have onMessageReceived() callback, which is triggered every time a notification comes.
Now Do this in your onMessageReceived() callback:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if(remoteMessage.getNotification() != null) {
if (AppPreferences.getInstance().getBoolean("IS_CHAT_ACTIVITY", false)) {
//Do Nothing, Ignore Notification
} else {
//Write code to show notification here
//Show Notification
generateNotification(remoteMessage.getNotification());
}
}
}
That's it, that's how you can prevent the notification while you’re on ChatActivity.
I have typed the following function to get notifications in android.
But I get an error which says Failed to post notification on channel "null". I know that I'm missing some piece of code which seems to be inserted for devices running on some newer versions.
Can I get the exact code to be inserted?
void create_notification(String string){
Intent intent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setContentIntent(pendingIntent)
.setContentText(string)
.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
}
In your builder, you can add the channelID, for example:
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setAutoCancel(true)
.setChannelId("base_channel") //<-- set the name you feel is proper to your project
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setContentIntent(pendingIntent)
.setContentText(string)
.build();
The documentation (first result on google for the search terms "android notification channel") gives the following example:
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
And then on your notification you need to specify the channel ID:
Notification notification = new Notification.Builder(this, CHANNEL_ID)
...
Have you tried this?
I searched many other questions related to this topic but found not satisfactory answer also none of them are working for me.
I want to show a continuous notification which should only be terminated by app. But the code i wrote was working a few days ago but not now.
private void GenNotification(String title, String body)
{
try
{
Log.i(Config.TAGWorker, "Generating Notification . . .");
Intent myIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this,
0,
myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(body)
.setChannelId("myID")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(false)
.setSmallIcon(R.drawable.floppy)
.setOngoing(true)
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, notification);
}
catch (Exception e)
{
Log.e(Config.TAGWorker, e.getMessage());
}
}
There is no exception recorded in Logcat, regarding ths. The code is called in onCreate of service. The service is starting correctly i can see in Log cat also there is no exception but notification is not shown. My OS is Android ONE for nokia (PI)
You are using a deprecated NotificationCompat.Builder constructor which takes a single argument (context); and that won't work on starting from Android 8.0 (API level 26).
So, to solve this:
Step 1: Create a Notification channel with the NotificationManager
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Notification channels are only available in OREO and higher.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel
("PRIMARY_CHANNEL_ID",
"Service",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("Description");
mNotificationManager.createNotificationChannel(notificationChannel);
}
Note: changeargument values as you wish
Step 2:: Use the non-deprecated Notification.Builder class with its two-argument constructor that takes a second argument as the channel ID which you assigned in the first step, where I set it to "PRIMARY_CHANNEL_ID"
Notification notification = new NotificationCompat.Builder
(this, "PRIMARY_CHANNEL_ID")
.setContentTitle("title")
.setContentText("body")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher_background)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOngoing(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setAutoCancel(true)
.build();
mNotificationManager.notify(0, notification);
Did you check your strings (title and body) is not null if it's null notification wont show
Also check that you call your notification channels when you start your service every time if your android above 7.0
Clear notification when you recall it same id in your case is 1.
Faced with the problem of displaying notifications in android Lollipop. When app is open notifications shows app fine, but when the application is closed they are not displaying. On 4x versions of android everything works properly. Here is a method to display them
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void sendNotification(String body, String title, String badge) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("from_notify", true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, Integer.valueOf(badge), intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(title)
.setContentText(body)
.setPriority(Notification.PRIORITY_HIGH)
.setShowWhen(true)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
I think this is the problem:
when your app is closed,all app's data will be cleared including the notifications and statics data,so if you want to make notifications alive all the time you have to send it from service(create service class and run it in the background).
try this:
public class YourService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//send your notifications here
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
note that you can send notifications from other classes not just from service class,but you have to run a service in the background because it helps to keep statics data for your app after it is closed.this worked for me.
I hope this will help you.