How to make text appear in an android notification? - android

I am trying to create a notification on android in order to notify the user if something is happening. Here is my example code (called from the MainActivity)
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.stoxx_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int mId = 1001;
mNotificationManager.notify(mId, mBuilder.build());
The notification is shown on the screen (no lock screen, the normal un-locked screen) and when I swipe the notification bar down (like Figure 2 in the documentation) I can see it as well, but the text is like follows:
MyApplication
Contents hidden
I was expecting to see the following content:
My notification
Hello World!
I looked in the documentation but did not find anything that I can use to solve my problem(I looked at setVisibility, but this seems to be relevant for a lock-screen only which I do not have here). Maybe I overlooked it, but maybe this does nothing have to do with a Notification. Any idea how to solve this problem?
Setting setVisibility(NotificationCompat.VISIBILITY_PUBLIC) makes the text readable even on the lock screen (not what I want) and setVisibility(NotificationCompat.VISIBILITY_SECRET) does not show the notification on the lock screen at all.
What I want:
lock-screen: notification is shown with 'Contents hidden'
unlocked screen: notification is shown with content as given in the code.
What I get with VISIBILITY_PRIVATE:
lock-screen: notification is shown with 'Contents hidden'
unlocked screen: notification is shown with 'Contents hidden'
What I get with VISIBILITY_PUBLIC:
lock-screen: notification is shown with with content as given in the code.
unlocked screen: notification is shown with with content as given in the code.
What I get with VISIBILITY_SECRET:
lock-screen: notification is not shown at all.
unlocked screen: unknown

Related

How to programatically minimize a Notification on Android [duplicate]

I would like to have an ongoing notification for my ForegroundService that requires as small place as possible. I like the "Android System - USB charging this device" style, but I cannot find any example how to achieve this.
Can anyone point me in the right direction?
Update
The style is given to the notification if the channel is assigned the importance IMPORTANCE_MIN.
It looks like there is no way to use Androids built in style for notifications of IMPORTANCE_MIN to be used with a ForegroundService.
Here is the description of IMPORTANCE_MIN:
Min notification importance: only shows in the shade, below the fold. This should not be used with Service.startForeground since a foreground service is supposed to be something the user cares about so it does not make semantic sense to mark its notification as minimum importance. If you do this as of Android version Build.VERSION_CODES.O, the system will show a higher-priority notification about your app running in the background.
To display a compact single line notification like the charging notification, you have to create a Notification Channel with priority to IMPORTANCE_MIN.
#TargetApi(Build.VERSION_CODES.O)
private static void createFgServiceChannel(Context context) {
NotificationChannel channel = new NotificationChannel("channel_id", "Channel Name", NotificationManager.IMPORTANCE_MIN);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(channel);
}
And then create an ongoing notification like that:
public static Notification getServiceNotification(Context context) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "channel_id");
mBuilder.setContentTitle("One line text");
mBuilder.setSmallIcon(R.drawable.ic_notification);
mBuilder.setProgress(0, 0, true);
mBuilder.setOngoing(true);
return mBuilder.build();
}
NOTE
Please note that I've tested it with an IntentService instead of a Service, and it works. Also I've just checked setting a Thread.sleep() of 15 seconds and the notification is showing perfectly until the IntentService stops itself.
There are some images (sorry some texts are in Spanish, but I think the images are still useful):
And if you drag down and opens the notification, it's shown as follows:
EXTRA
If you notice that Android System shows a notification indicating all apps which are using battery (apps with ongoing services), you can downgrade the priority of this kind of notifications and it will appear as one line notifications like the charging notification.
Take a look at this:
Just long click on this notification, and select ALL CATEGORIES:
And set the importance to LOW:
Next time, this "battery consumption" notification will be shown as the charging notification.
You need to set the Notification priority to Min, the Notification Channel importance to Min, and disable showing the Notification Channel Badge.
Here's a sample of how I do it. I've included creating the full notification as well for reference
private static final int MYAPP_NOTIFICATION_ID= -793531;
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
String CHANNEL_ID = "myapp_ongoing";
CharSequence name = context.getString(R.string.channel_name_ongoing);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_MIN);
channel.setShowBadge(false);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_notification_add_reminder)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(context.getString(R.string.create_new))
.setOngoing(true).setWhen(0)
.setChannelId(CHANNEL_ID)
.setPriority(NotificationCompat.PRIORITY_MIN);
// Creates an intent for clicking on notification
Intent resultIntent = new Intent(context, MyActivity.class);
...
// The stack builder object will contain an artificial back stack
// for the
// started Activity.
// This ensures that navigating backward from the Activity leads out
// of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MyActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(MYAPP_NOTIFICATION_ID, mBuilder.build());
To answer the original question:
There seems to be no built-in way on Android O to get a single line, ongoing notification for a ForegroundService. One could try adding a custom design, but as different phones have different designs for notification, that solution is hardly a good one.
There is hope, however :)
On Android P the notification in a NotificationChannel of IMPORTANCE_LOW with a priority of PRIORITY_LOW is compacted to a single line even for a ForegroundService. Yeah!!
I made the size of foreground service notification smaller by creating an empty custom view like this:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
and then creating the notification like this:
RemoteViews notifiactionCollapsed = new RemoteViews(getPackageName(),R.layout.notification_collapsed);
Notification notification = new NotificationCompat.Builder(this,CHANNEL_ID)
.setSmallIcon(R.drawable.eq_icon)
.setCustomContentView(notifiactionCollapsed)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setShowWhen(false)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true)
.setVisibility(NotificationCompat.VISIBILITY_SECRET)
.build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
This helps in reducing the height of the notification but still I am not sure about how to hide the notification icon.

White Square is displayed instead of my notification icon [duplicate]

This question already has answers here:
Android Push Notifications: Icon not displaying in notification, white square shown instead
(21 answers)
Closed 5 years ago.
I'm trying to build my own notification as soon as I receive a payload from my server in my FCM Receiver, I set my notification icon to my app icon which is in PNG Format, however, my notification is displayed with a white square instead and I don't know why..
Here's my code:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.icon)
.setContentTitle("Your chat is going to expire tomorrow!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, main_activity.class);
resultIntent.putExtra("launchedFromNotification",true);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your app to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(main_activity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mNotificationId is a unique integer your app uses to identify the
mNotificationManager.notify(MESSAGE_NOTIFICATION_ID, mBuilder.build());
This usually happens when you use a non-alpha icon
When you use icons on your notification, android paints over all non-alpha (non-transparent) parts of the icon. This means if you use a square image as your notification icon, it would just come out as a white square.
To fix this, just use a shape-like icon. Check below for reference:
Icon Reference

Create custom notification including Edit text android

I wanna create a custom notification to reply SMS directly from notification like this:
As I have understood normal notifications must have 64dp height but you can use bigger one from API >16 as expandable notification but I think 64dp height is suitable for my case. I used this code but it crashes when my custom notification layout has edit text:
RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.widget);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContent(remoteViews);
Intent resultIntent = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(100, mBuilder.build());
Error:
android.app.RemoteServiceException: Bad notification posted from package com.example.x: Couldn't expand RemoteViews for: StatusBarNotification
What should I do?
Create custom notification including Edit text android
You cannot put an EditText widget into a Notification, app widget, or anything else that uses RemoteViews.
why?
Because that is how RemoteViews is written. You are limited to certain widgets and containers.
what should I do to make that custom notification?
Re-design it to not involve an EditText.
UPDATE: On Android 7.0+, you can use a MessagingStyle with RemoteInput to accept input from the user from a Notification. This does not match the requirements of the question, but it is the closest option.

Do something when my app's notification is triggered

I'd like an activity of my app to listen when a specific notification is received and do something then.
The notification is triggered from within the app itself. I'm kind of new to Android development (and to development in general) so here's some pseudocode for what I want to do:
Activity{
notificationListener(){
if(notification is received){
//Do something
}
}
Any help would be much appreciated.
After checking the API of Notification, there seems no way to listen to sending Notification. After thinking deep, you would understand why we can't. AFAYK, it is we that write codes to send Notification but not the system, right? We surely know when we send Notifications, right? So, if you want to know when Notification is sent, why not do something, like sending BroadcastReceiver or starting Service to let other codes noticed? It all depends on our code-writers. And here is how to customize a Notification:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());

PendingIntent opens main activity instead of desired activity

I am creating an android application that shows a notification in a Service.
I show the notification exactly as mentioned in documentation. It works fine and the PendingItent object starts the desired activity.
But after a while when I close and restart the application a couple of times, tapping on the notification will start the Main Activity (which is the parent of desired activity) instead of the desired activity.
The only way I found to fix that is to restart the device. (Clearing app's cache and uninstalling didn't help.
I googled my problem and also searched here a lot, but couldn't find anything relevant.
seems that I'm the only one having this problem.
Could anyone please help me with this problem?
Thanks in advance;
EDIT:
as I said, I do exactly like the documentation. But here is my code anyway:
Intent resultIntent = new Intent(this, MyActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MyActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Title")
.setContentText("Body");
builder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(457, builder.build());

Categories

Resources