Notification content text being changed based on different scenarios - android

I am building an app which shows notification when a new message arrives.I have successfully implemented the notification part-but there, I am facing some weird issue while viewing my shown notifications -it is showing different content text based on different scenarios-I am including the 2 cases-
a)when the notifications arrives
b)when I slide down the notification tray to see my notifications
As you can clearly see the differences in the content-text in two different cases- Why is it happening ?
I am attaching the code which I have implemented to build the notifications-
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String identifyDataType = remoteMessage.getData().get(getString(R.string.data_type));
//SITUATION: Application is in foreground then only send priority notificaitons such as an admin notification
Log.d(TAG, "Data type: data: " +identifyDataType);
if(identifyDataType.equals(getString(R.string.data_type_admin_broadcast))){
//build admin broadcast notification
String title = remoteMessage.getData().get(getString(R.string.data_title));
String senderId=remoteMessage.getData().get(getString(R.string.sender_of_message));
String message = remoteMessage.getData().get(getString(R.string.data_message));
Log.d(TAG,"TITL AND MESSG"+title+message);
sendBroadcastNotification(title, message,senderId);
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void sendBroadcastNotification(String title, String message, String senderId){
Log.d(TAG, "sendBroadcastNotification: building a admin broadcast notification with "+title+" "+message);
NotificationChannel mChannel=null;
// Instantiate a Builder object.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default_channel_id");
// Creates an Intent for the Activity
Intent notifyIntent = new Intent(this, MainActivity.class);
notifyIntent.putExtra("Id", "none");
Log.d("messsagingService Title",title);
notifyIntent.putExtra("Name", title.split(":")[1].trim());
// Sets the Activity to start in a new, empty task
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Creates the PendingIntent
PendingIntent notifyPendingIntent =
PendingIntent.getActivity(
this,
0,
notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mChannel = new NotificationChannel("default_channel_id", getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
mChannel.setDescription(message);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
//add properties to the builder
builder.setSmallIcon(R.drawable.icons1)
.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.icons1))
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentTitle(title)
.setContentText(message)
.setColor(getResources().getColor(R.color.blue_btn_bg_color))
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(title).setSummaryText(message))
.setNumber(mNumPendingMessages)
.setOnlyAlertOnce(true);
builder.setContentIntent(notifyPendingIntent);
mNotificationManager.notify(BROADCAST_NOTIFICATION_ID, builder.build());
}
Any help is very much solicited -why this is even happening! Thank you.

Related

samsung wear watch notification issue

Im trying to show notification on wear watch anything is goes correct but My Remote input choice are not visible on samsung watch it will show only title and Body my input choice are not visible on it.
It appears on my phone, but it doesn't appear on my watch connected to my phone. Is there something missing from the code that's required for Android Wear?
I'm using this code for display notification on watch
public void getNotifcation(){
RemoteInput ri = new RemoteInput.Builder(KEY_TEXT_REPLY) .setLabel(body) .setChoices(replyChoices) .build();
NotificationCompat.Action a =
new NotificationCompat.Action.Builder(R.drawable.ic_send_arraow_red,
null, getReplyPendingIntent())
.addRemoteInput(ri)
.build();
Uri defaultSoundUri = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_noti_icon)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification))
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setVibrate(new long[]{200, 400, 600, 800})
.setOngoing(false)
.setGroup("GROUP")
.setGroupSummary(false)
.setContentIntent(notifyPendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.addAction(a)
.extend(new NotificationCompat.WearableExtender().addAction(a));
NotificationCompat.WearableExtender extender =
new NotificationCompat.WearableExtender();
extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_send_arraow_red, "send" ,
getReplyPendingIntent())
.addRemoteInput(ri).build());
notificationBuilder.extend(extender);
//Wear OS requires a hint to display the reply action inline.
NotificationCompat.Action.WearableExtender actionExtender =
new NotificationCompat.Action.WearableExtender()
.setHintLaunchesActivity(true)
.setHintDisplayActionInline(true);
notificationBuilder.addAction(noti.extend(actionExtender).build());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId, "Notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription(messageBody);
notificationChannel.enableLights(true);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{200, 400, 600, 800});
notificationChannel.setLightColor(Color.RED);
if (defaultSoundUri != null) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
notificationChannel.setSound(defaultSoundUri, audioAttributes);
}
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(notificationId notificationBuilder.build());
}
and here is my pending intent to get choice on wear
public void getReplyPendingIntent(){
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // start a // (i) broadcast receiver which runs on the UI thread or // (ii) service for a background task to b executed,will be doing a broadcast receiver
intent = new Intent(context, FcmBroadcastReceiver.class);
intent.setAction(REPLY_ACTION);
intent.putExtra(KEY_NOTIFICATION_ID, notificationId);
intent.putExtra(KEY_TEXT_REPLY, KeyReply);
return PendingIntent.getBroadcast(getApplicationContext(), 100, intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
} else {
// start your activity
intent = Act_Home.getReplyMessageIntent(this, notificationId, 123);
return PendingIntent.getActivity(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
}
}

Heads up Notification not working as expected

I have Implemented heads up notification for my app. Code is like this:
private String CHANNEL_ID = "message_notifications";
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID,"message_notifications", NotificationManager.IMPORTANCE_HIGH);
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String notification_title = remoteMessage.getNotification().getTitle();
String notification_message = remoteMessage.getNotification().getBody();
String click_action = remoteMessage.getNotification().getClickAction();
String user_id = remoteMessage.getData().get("user_id");
String user_name = remoteMessage.getData().get("user_name");
String GROUP_KEY_CHIT_CHAT = "com.android.example.Chit_Chat";
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.chitchat_icon)
.setContentTitle(notification_title)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setGroup(GROUP_KEY_CHIT_CHAT)
.setDefaults(Notification.DEFAULT_ALL)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setContentText(notification_message);
if (Build.VERSION.SDK_INT >= 21) mBuilder.setVibrate(new long[0]);
Intent resultIntent = new Intent(click_action);
resultIntent.putExtra("user_id", user_id);
resultIntent.putExtra("user_name",user_name);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(resultIntent);
stackBuilder.addParentStack(MainActivity.class);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mChannel.setShowBadge(true);
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
mNotificationManager.createNotificationChannel(mChannel);
mBuilder.setChannelId(CHANNEL_ID);
}
mNotificationManager.notify(mNotificationId,mBuilder.build());
}
Problem is It only works correctly when I do the settings for the notification as popup and sound else it appears like simple notification. Whatsapp and other applications are by default settuped to use them. I want to do the same. I want to programmatically set the settings for my app to use heads up notification by default without going into the setting to enable it. Can anybody help me how to do that?
I need to set it to sound and popup it doesn't set by default
Set the importance level of notification channel to IMPORTANCE_HIGH to appears as a heads-up notification.
Set notification as ongoing using setOngoing method if you want the notification dismissed only while performing an action. Ongoing notifications cannot be dismissed by the user, so your application or service must take care of canceling them.
If you want to show the notification in Do Not Disturb mode as well you can set category to CATEGORY_ALARM
If you want an intent to launch instead of posting the notification to the status bar for demanding the user's immediate attention use setFullScreenIntent
Sample code block
Intent launch = new Intent(context, TargetActivity.class);
launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0,
launch, PendingIntent.FLAG_UPDATE_CURRENT);
createNotificationChannel(mContext, NOTIFICATION_CHANNEL_ID, NotificationManager.IMPORTANCE_HIGH,
R.string.notification_channel_name, R.string.notification_channel_description);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID);
builder.setContentTitle("Title");
builder.setContentText("Content Text");
builder.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Big Content Text"));
builder.setSmallIcon(R.drawable.status_icon);
builder.setFullScreenIntent(pendingIntent, true);
builder.setOngoing(true);
builder.setAutoCancel(true);
builder.setCategory(NotificationCompat.CATEGORY_ALARM);
builder.addAction(0, "Action Text", pendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
notificationManager.notify(COMPLETE_NOTIFICATION_ID, builder.build());
/**
* create Notification channel
* #param context
* #param channelId
* #param channelName
* #param channelDescription
*/
#RequiresApi(api = Build.VERSION_CODES.O)
public static void createNotificationChannel(Context context, String channelId, int importance, int channelName, int channelDescription) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = context.getString(channelName);
String description = context.getString(channelDescription);
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}

Not getting Large Icon when app is not in background

I am setting large icon for push notification by using following code.
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.logo)
.setContentTitle(notification.getTitle())
.setContentText(notification.getBody())
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.green))
.setSound(defaultSoundUri)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo))
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent);
This works fine and shows largeIcon when app is in foreground, but when app is not in foreground, it does not display large icon.
I am testing the app in samsung s7(oreo)
The code snipped you posted works fine only when your app is in the foreground because it only gets called when the app is in the foreground. When the application is in the background, the Android system displays the notification for you (based on the 'notification' object in the JSON object that the server sends to the device). Your receiver is not being called at all. Currently, Firebase Cloud Messaging doesn't support setting a large icon as a payload in the request.
A way around this is to not include a 'notification' object in the POST payload of the message. When you only include 'data' object in the payload, your receiver will be asked to handle the notification even when your application is in the background. Then, you can build the notification the same way as if the app was in the foreground and set a large icon for the notification.
Take a look at this answer for a more detailed explanation about this issue.
Try this,
you're recommended to set default values to customize the appearance of notifications. You can specify a custom default icon and a custom default color that are applied whenever equivalent values are not set in the notification payload.
Add these lines inside the application tag to set the custom default icon and custom color:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_ic_notification" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
Set your application icon transparent
android:icon="#drawable/icon_transper"
and add this lime in AndroidManifest
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/gardi" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
If you set your application icon transparent it can take as notification icon in background.
prefer this link to generate notification icon.
https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=clipart&source.clipart=ac_unit&source.space.trim=1&source.space.pad=0&name=ic_stat_ac_unit
I hope this can help you!
Thank You.
It's because you've to set the large icon first and small icon second to that, also you shouldn't use vector images as large icon. Use either Jpeg or PNG images.
new NotificationCompat.Builder(this, channelId)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo))
.setSmallIcon(R.drawable.logo)
.setContentTitle(notification.getTitle())
.setContentText(notification.getBody())
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.green))
.setSound(defaultSoundUri)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent);
try once.. Where are you storing your icon in drawable folder .. all the folders like hdpi, xhdpi, xxhdpi.. pls try this once..
You need to check version. If version >= Oreo than you need to add channel id. Please see the sample code below which is working for me:
public void createNotification(Bitmap bitmap, String aMessage, Context context, int icon, String titles, String noti_id, String mid, String att_url, String mname) {
NotificationManager notifManager = null;
final int NOTIFY_ID = 0; // ID of notification
String id = context.getString(R.string.default_notification_channel_id); // default_channel_id
// String title = context.getString(R.string.default_notification_channel_id); // Default Channel
String title = titles;
Intent intent;
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.setBigContentTitle(title);
String msg = aMessage;
// bigPictureStyle.setSummaryText("Summary text appears on expanding the notification");
bigPictureStyle.setSummaryText(msg);
bigPictureStyle.bigPicture(bitmap);
if (notifManager == null) {
notifManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
String m_namse = "Marwadi University - " + mname;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = notifManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, title, importance);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notifManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(context, id);
intent = new Intent(context, FullScreenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// List<String> test = new ArrayList<String>();
// test.add();
intent.putExtra("title", titles);
intent.putExtra("body", aMessage);
ConstantData.setNotificaitonId(context);
// ConstantData.getNotificaitonId(context);
bundle.putString("values", str);
intent.putExtra("img_path", imageUri);
intent.putExtra("n_id", noti_id);
intent.putExtras(bundle);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(R.drawable.mu_top_white) // required
.setContentText(m_namse) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setStyle(bigPictureStyle)
.setContentIntent(pendingIntent)
.setTicker(aMessage)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
} else {
builder = new NotificationCompat.Builder(context, id);
// intent = new Intent(context, AllNotificationActivity.class);
intent = new Intent(context, FullScreenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("title", titles);
intent.putExtra("body", aMessage);
// intent.putExtra("img_path", imageUri);
intent.putExtra("img_path", imageUri);
intent.putExtra("n_id", noti_id);
intent.putExtra("mid", mid);
ConstantData.setNotificaitonId(context);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(R.drawable.mu_top_white) // required
.setContentText(m_namse) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setStyle(bigPictureStyle)
.setContentIntent(pendingIntent)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setTicker(aMessage)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(Notification.PRIORITY_HIGH);
}
Notification notification = builder.build();
notifManager.notify(NOTIFY_ID, notification);
}
And then Simple call this method:
createNotification(bitmap, message, mContext, R.drawable.main_logo, title, noti_id, mid, att_url, msg);

Firebase Push Notification?

I am implementing firebase push notification in my app, the app is showing the push notification also. But my problem is - I may send different types of push notifications based on different topics.
Ex -
1. If I am sending a push notification on App Update, then on clicking that notification by the user, he should be redirected to PlayStore
If I am sending a push notification on New Contents, then on clicking that notification by the user, he should be redirected to App's MainActivity
If I am sending a push notification on New Contest, then on clicking that notification by the user, he should be redirected to App's ContestActivity
I implemented it using the below code in "MessageReceiver" class as --
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getNotification().getTitle();
String message = remoteMessage.getNotification().getBody();
showNotifications(title, message);
}
private void showNotifications(String title, String msg) {
Intent i = null;
if(title.equals("DoUp Now - Update")){
Uri uri = Uri.parse("https://play.google.com/store/apps/details?id=com.s2s.doupnow"); // missing 'http://' will cause crashed
i = new Intent(Intent.ACTION_VIEW, uri);
}
else if(title.equals("DoUp Now - New Content")){
i = new Intent(this, MainActivity.class);
}
else if(title.equals("DoUp Now - New Notification")){
i = new Intent(this, NotificationActivity.class);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, REQUEST_CODE,
i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder, mBuilderOld;
final int NOTIFICATION_ID = 1;
final String NOTIFICATION_CHANNEL_ID = "my_notification_channel";
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
mNotifyManager.createNotificationChannel(notificationChannel);
mBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
mBuilder.setContentTitle(title)
.setContentText(msg)
.setSmallIcon(R.drawable.doupnowlogo)
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
}
else
{
mBuilderOld = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
mBuilderOld.setContentTitle(title)
.setContentText(msg)
.setSmallIcon(R.drawable.doupnowlogo)
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationManager.IMPORTANCE_MAX);
mNotifyManager.notify(NOTIFICATION_ID, mBuilderOld.build());
}
}
But on clicking any notification by the user, he is always redirected to App's MainActivity only.
Can anyone guide me where i am missing.
If you are comparing title using api the you have to check the title using JSON object like this.
JSONObject data = json.getJSONObject("data");
String title = data.getString("title");
String message = data.getString("message");
Make sure the title you get is equal as title you are comparing and add flags in intent.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

How to update a notification without notifying in Android?

So I have an app that receives the temperature via MQTT. To avoid getting spammed by notifcations, I want the app to notify once, that is vibrate, play sound and then the next three times (if the notification isn't dismissed) it will only update the temperature value. So:
Notify
Update temp
Update temp
Update temp
5(or 1 if you will) Notify
This is my code:
private final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, id);
private void handleNotification(String message, String topic) {
if (notifManager == null) {
notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
if (isNotifRunning() && ticker < 3) {
updateNotif(message);
ticker++;
} else {
createNotif(message);
ticker = 0;
}
}
private void createNotif(String message) {
Intent intent;
PendingIntent pendingIntent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = notifManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200});
notifManager.createNotificationChannel(mChannel);
}
intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentTitle(getString(R.string.notifTmpLowTitle))
.setSmallIcon(R.drawable.ic_ac_unit_black_24px)
.setContentText(getString(R.string.notifTmpLowText) + " " + message + Constants.CELSIUS)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker(message)
.setColor(getResources().getColor(R.color.colorCold))
.setVibrate(new long[]{100, 200});
} else {
intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentTitle(getString(R.string.notifTmpLowTitle))
.setSmallIcon(R.drawable.ic_ac_unit_black_24px)
.setContentText(getString(R.string.notifTmpLowText) + " " + message + Constants.CELSIUS)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker(message)
.setVibrate(new long[]{100, 200})
.setColor(getResources().getColor(R.color.colorCold))
.setPriority(Notification.PRIORITY_HIGH);
}
Notification notification = builder.build();
notifManager.notify(NOTIFY_ID, notification);
}
//TODO Doesn't update, posts a new notification.
private void updateNotif(String message) {
builder.setContentText(getString(R.string.notifTmpLowText) + " " + message + Constants.CELSIUS);
Notification notification = builder.build();
notification.flags = Notification.FLAG_ONGOING_EVENT;
notifManager.notify(NOTIFY_ID, notification);
}
//---------------------------------------------
With this code, I always get, what it looks like, a brand new notification with sound and vibration. I've looked at previous questions regarding this and they all say that it's important to use the same builder and as you can see, I have done this. Is there some change in newer Android versions that I'm not aware of? I've tested on both 7.1.1 and 8.1.
You'll want to call setOnlyAlertOnce(true) to cause updates to your notification to not send sound/vibration.

Categories

Resources