I'm having trouble getting Android's Big Text notifications to work as documented here: NotificationCompat.BigTextStyle. Here's the code I'm using to display notifications. I know all the data is coming back correctly because I can get it to display on the console and as the traditional content text and title. Am I doing something wrong? Do I need to define bigTestStyle somewhere else as well? Hopefully one of you has done this before and knows what could be missing. Thanks.
My code:
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.bigText(extras.getString("message"));
NotificationCompat.Builder bigTextNotification = new NotificationCompat.Builder(context)
.setContentTitle("My App")
.setContentIntent(pendingIntent)
.setContentText("Message:")
.setSound(soundUri)
.setTicker(extras.getString("message"))
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.splash)
.setAutoCancel(true)
.setVibrate(new long[] { 0, 100, 200, 300 })
.setStyle(bigTextStyle);
final int notificationId = (int) (System.currentTimeMillis() / 1000L);
NotificationManager thisone = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
thisone.notify(notificationId, bigTextNotification.build());
From NotificationCompat.BigTextStyle documentation :
Helper class for generating large-format notifications that include a lot of text.
If the platform does not provide large-format notifications, this method has no effect. The user will always see the normal notification view.
Perhaps your platform doesn't support large-format notifications.
EDIT :
On the other hand, it's possible your problem is here :
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.bigText(extras.getString("message"));
You are not using the return value of bigText.
Try to change it to :
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle = bigTextStyle.bigText(extras.getString("message"));
or to :
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle().bigText(extras.getString("message"));
EDIT2 :
Costom Notification Layout for older Android versions :
protected void onMessage(Context context, Intent intent) {
// Extract the payload from the message
Bundle extras = intent.getExtras();
if (extras != null) {
String message = (String) extras.get("message");
String title = (String) extras.get("title");
// add a notification to status bar
NotificationManager mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent myIntent = new Intent(this,MyActivity.class);
Notification notification = new Notification(R.drawable.notification_image, title, System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
contentView.setImageViewResource(R.id.image, R.drawable.notification_image);
contentView.setTextViewText(R.id.title, title);
contentView.setTextViewText(R.id.text, message);
notification.contentView = contentView;
notification.contentIntent = PendingIntent.getActivity(this.getBaseContext(), 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
mManager.notify(0, notification);
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
wl.acquire(15000);
}
}
Related
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);
}
}
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);
I am working on an application which sends device to device push notification. I have created a custom notification layout which has a heading, message and two buttons (Accept and Reject). When device B receives a notification from Device A, for some phones it works perfectly, but in some phones the notification tray fails to display the title, message and buttons. It just shows a blank notification tray. Its not an error, but the custom layout doesn't load for some phones. It works perfectly in Moto G5s plus (Android 7.1.1), but doesn't work for RedMi Note 5 Pro, same API level (Android 7.1.1). Can anyone help me with this?
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> remoteMessageData = remoteMessage.getData();
String remoteMessageType = remoteMessageData.get("type");
String message = remoteMessageData.get("message") + ". Please Confirm?";
String profilePhoto = remoteMessageData.get("profile_photo");
String notificationUID = remoteMessageData.get("notification_uid");
String userUID = remoteMessageData.get("user_uid");
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_custom_notification);
remoteViews.setTextViewText(R.id.textNotificationMessage, message);
remoteViews.setImageViewBitmap(R.id.eIntercomProfilePic, getBitmapFromURL(profilePhoto));
Notification notification = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.namma_apartment_notification)
.setAutoCancel(true)
.setCustomBigContentView(remoteViews)
.setSound(RingtoneManager.getDefaultUri(Notification.DEFAULT_SOUND))
.setPriority(PRIORITY_DEFAULT)
.build();
int mNotificationID = (int) System.currentTimeMillis();
Intent acceptButtonIntent = new Intent("accept_button_clicked");
acceptButtonIntent.putExtra("Notification_Id", mNotificationID);
acceptButtonIntent.putExtra("Notification_UID", notificationUID);
acceptButtonIntent.putExtra("User_UID", userUID);
PendingIntent acceptPendingIntent = PendingIntent.getBroadcast(this, 123, acceptButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.buttonAccept, acceptPendingIntent);
Intent rejectButtonIntent = new Intent("reject_button_clicked");
rejectButtonIntent.putExtra("Notification_UID", notificationUID);
rejectButtonIntent.putExtra("Notification_Id", mNotificationID);
rejectButtonIntent.putExtra("User_UID", userUID);
PendingIntent rejectPendingIntent = PendingIntent.getBroadcast(this, 123, rejectButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.buttonReject, rejectPendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
/*To support Android Oreo Devices and higher*/
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
getString(R.string.default_notification_channel_id), "Namma Apartments Channel", NotificationManager.IMPORTANCE_HIGH);
Objects.requireNonNull(notificationManager).createNotificationChannel(mChannel);
}
}
i think you talking about Oreo or above version. Oreo can not support notification for notification you need to create channel for that like below :
private void sendMyNotification(String message,String title) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.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");
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.listlogo)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.tlogo))
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationManager.IMPORTANCE_MAX)
.setOnlyAlertOnce(true)
.setChannelId("my_notification")
.setColor(Color.parseColor("#3F5996"));
//.setProgress(100,50,false);
notificationManager.notify(0, notificationBuilder.build());
}
My app get crash after receiving the notification it shows in Log Cat that NosuchMethodError for the line No 107 i.e. .setWhen(System.currentTimeMillis()).build(); in my file, can someone help,
My device version is 4.0+ and code is as follows
final Bundle bundle = intent.getExtras();
final Object systemService = context.getSystemService(Context.NOTIFICATION_SERVICE);
// Retrieve notification details from the intent
final String tickerText = bundle.getString(TICKER_TEXT);
final String message = bundle.getString(MESSAGE);
final String notificationTitle = bundle.getString(TITLE);
final String notificationSubText = bundle.getString(SUBTITLE);
int notificationId = 0;
Intent pintent = new Intent(context,MainActivity.class);
final PendingIntent contentIntent = PendingIntent.getActivity(context, 0, pintent, 0);
Notification notification = new Notification.Builder(context)
.setContentTitle(notificationTitle)
.setContentText(message)
.setTicker(tickerText)
.setAutoCancel(true)
.setSound(Uri.parse("android.resource://"+ context.getPackageName() + "/raw/horn"))
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(contentIntent)
.setWhen(System.currentTimeMillis()).build();
NotificationManager notificationMgr = (NotificationManager) systemService;
notificationMgr.notify(notificationId, notification);
Maybe because setWhen() was added only in API level 11. Check if you are running the project in any lower version devices.
If that's the case, then you have to go for backward compatibility and try to learn about it.
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(ns);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = title;
long when = System.currentTimeMillis();
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(alarmSound == null){
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
if(alarmSound == null){
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
}
Intent intent = new Intent();
PendingIntent pendingIntent
= PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.BigTextStyle bigxtstyle =
new NotificationCompat.BigTextStyle();
bigxtstyle.bigText(text);
bigxtstyle.setBigContentTitle(title);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setStyle(bigxtstyle)
.setSmallIcon(icon)
.setAutoCancel(true)
.setSound(alarmSound)
.setDeleteIntent(pendingIntent)
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));
Notification noti = mBuilder.build();
mNotificationManager.notify(notificationid++, noti);
This code works, and displays the text as advertised with word wrapping. However, when a subsequent notification happens the previous notification loses its text. Can anyone help resolve this issue? It could be something I'm setting incorrectly, I am new to the android apis.
Android only displays one expanded notification by default. Your notification doesn't lose its content, it just gets compressed and only shows the normal one-line content. But it seems that you don't specify this, therefore the compressed notification is empty.
You may use setContentTitle() and setContentText() to set the one-line texts.