Lesson 184. Android Notifications. Message. foundations

Lesson 184. Android Notifications. Message. foundations


Notifications are messages that the user sees at the top of the screen when he or she receives a new email, message, update, etc. In the next few lessons, we will take a closer look at what opportunities developers have for displaying messages.

In this tutorial, we will cover the basics of displaying / updating / deleting a message and handling it.

display

The simple message creation code looks like this:

NotificationCompat.Builder builder =
       new NotificationCompat.Builder(this)
               .setSmallIcon(R.mipmap.ic_launcher)
               .setContentTitle("Title")
               .setContentText("Notification text");

Notification notification = builder.build();

NotificationManager notificationManager =
       (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);

We use a builder that specifies an icon, title and text for the message. With the build method, we get a ready message.

Next, we use NotificationManager and its notify method to show the generated message. In addition to notification, you must pass an id. This is so that we can later use this id to update or delete the message.

The constructor of new NotificationCompat.Builder (Context) will be marked as Deprecated if you use the appCompat library of version 26 and above. It happened because a new constructor appeared in Android API 26 and it is recommended to use it. Don’t pay attention to it yet. In one of these lessons, we will look at using the right constructor.

When we run this code, we will see a message

It displays the icon and the two texts that we specified in the builder. Clicking on it will not lead to anything because we did not implement the click handler. We’ll do it later.

renewal

We have displayed the message and now want to recover it. To do this, simply show the message again using the notify method and use the same id.

It will look like this:

NotificationCompat.Builder builder =
       new NotificationCompat.Builder(this)
               .setSmallIcon(android.R.drawable.ic_dialog_email)
               .setContentTitle("Title change")
               .setContentText("Notification text change");

Notification notification = builder.build();

NotificationManager notificationManager =
       (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);

The code is exactly the same as the code we used to display the message. Only in the builder we use other texts and an icon. The most important thing is that in the notify method we again use id = 1. NotificationManager from this id will find the message we displayed a little earlier and replace it with a new one.

several messages

To display a new message rather than update an existing one, you must use a different id in the notify method.

the first message

NotificationCompat.Builder builder =
       new NotificationCompat.Builder(this)
               .setSmallIcon(R.mipmap.ic_launcher)
               .setContentTitle("Title")
               .setContentText("Notification text");

Notification notification = builder.build();

NotificationManager notificationManager =
       (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);

the second message

NotificationCompat.Builder builder =
       new NotificationCompat.Builder(this)
               .setSmallIcon(android.R.drawable.ic_dialog_email)
               .setContentTitle("Title 2")
               .setContentText("Notification text 2");

Notification notification = builder.build();

NotificationManager notificationManager =
       (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(2, notification);

We used different ids in the notify method and received two different messages

removal

To delete a message, we use NotificationManager and its cancel method, specifying the message id.

NotificationManager notificationManager =
       (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(1);

Or cancelAll can delete all messages at once

NotificationManager notificationManager =
       (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancelAll();

When you delete a message, you do not need to check whether it is displayed or not. If the message is gone for some reason, then nothing will happen.

Click processing

You must use PendingIntent to perform any action after clicking on the message. PendingIntent is an Intent container. This container can be used to further run the Intent attached to it.

We will create an Intent to run, for example, Activity, pack that Intent into PendingIntent, and pass PeningIntent to a message. When you click on a message, the system will retrieve PedningIntent from it and use its nested Intent to launch the Activity.

Let’s see how this looks in practice:

Intent resultIntent = new Intent(this, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent,
               PendingIntent.FLAG_UPDATE_CURRENT);

We create Intent to run Activity and pack it into PedningIntent.

You can read more about PedningIntent and its parameters in Lesson 119. There, I examined in detail the different cases on the BroadcastReceiver message and call examples.

The created PendingIntent we will need to send to the builder of the message. The full message creation code will look like this:

// Create PendingIntent
Intent resultIntent = new Intent(this, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent,
               PendingIntent.FLAG_UPDATE_CURRENT);

// Create Notification
NotificationCompat.Builder builder =
       new NotificationCompat.Builder(this)
               .setSmallIcon(R.mipmap.ic_launcher)
               .setContentTitle("Title")
               .setContentText("Notification text")
               .setContentIntent(resultPendingIntent);

Notification notification = builder.build();

// Show Notification
NotificationManager notificationManager =
       (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);

We pass PendingIntent to the message builder setContentIntent method.

Clicking on the message will open MainActivity

Note that the message is not automatically deleted after clicking on it. To fix this, you can use the autoCancel parameter in the message builder

setAutoCancel(true)

The message created with this flag will be closed after clicking on it.

Message Builder has a few more methods that can be helpful.

setNumber – Adds a number to a message

setContentInfo – Adds text to the right

In the old versions it looks like this

In recent versions, it has moved to the top of the message

setColor – will add a background color to the icon

setWhen – you can specify your own time for the message (when). By default when = message creation time

setShowWhen – Show whether time is in the message

setUsesChronometer – Instead of a static time, a counter (00:00) will be displayed in the message, indicating how much time has elapsed since. It may be useful for a stopwatch or a call.

setOngoing – such message cannot be closed or removed by the user. It will be displayed on top of regular messages.

setVibrate, setSound, setLights – device vibration, sound and LED settings

setPriority – Ability to set priority. Available values ​​are -2 (NotificationCompat.PRIORITY_MIN) to 2 (NotificationCompat.PRIORITY_MAX). The behavior may differ across Android versions, but the overall meaning is the same – the higher the priority, the higher the likelihood that the user will see your message.

setTimeoutAfter – the ability to set a timeout (in ms) after which the message itself will be deleted. Added to API 26.

setLargeIcon – the ability to set your picture as a message icon.

BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.startandroid, options);

NotificationCompat.Builder builder =
        new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Title")
                .setContentText("Notification text")
                .setLargeIcon(bitmap);

The icon from setSmallIcon will be visible in the status bar when the message bar is not opened.

The message itself will look like this:

setProgress – the ability to display the progress bar in the message

The method has three parameters:

max – the maximum value of the progress bar. Enter 0 if you want to hide the progress bar.

progress – the current value of progressbar. May be from 0 to max.

indeterminate – if true, an “infinite” progress bar will be displayed

Consider an example:

int max = 100;

// show notification with indeterminate progressbar
builder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("Some operation")
        .setContentText("Preparing")
        .setProgress(max,0, true);

notificationManager.notify(1, builder.build());


new Thread(new Runnable() {
    @Override
    public void run() {

        try {TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        int progress = 0;

        while (progress < max) {

            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            progress += 10;

            // show notification with current progress
            builder.setProgress(max, progress, false)
                    .setContentText(progress + " of " + max);
            notificationManager.notify(1, builder.build());

        }

        // show notification without progressbar
        builder.setProgress(0, 10, false)
                .setContentText("Completed");
        notificationManager.notify(1, builder.build());
    }
}).start();

First, we display the infinite progress bar and the Preparing text. That is, we pretend to be preparing for the operation.

Then, in a separate thread, we simulate the operation. Every 300 ms we increase the value of progress and update the message so that the progress bar shows the current progress. And also in the text we show the values ​​of progress and maximum.

After performing the operation, we hide the progress bar and display Completed text.

Again, I highly recommend reading and understanding Lesson 119. In it, I explore in detail why the PendingIntent of the last message replaces the PendingIntent of the previous messages, and how this can be avoided using, for example, requestCode.




Discuss in the forum [3 replies]

Leave a Comment