Skip to content

Instantly share code, notes, and snippets.

@MohammadSamandari
Last active April 3, 2020 23:38
Show Gist options
  • Save MohammadSamandari/c685dd57ccd86adf8d9ecd9ed1c9b983 to your computer and use it in GitHub Desktop.
Save MohammadSamandari/c685dd57ccd86adf8d9ecd9ed1c9b983 to your computer and use it in GitHub Desktop.
Notification

Notification

No need to explain.

Notification Channels

In the Settings app on an Android-powered device, users can adjust the notifications they receive. Starting with Android 8.0 (API level 26), you can assign each of your app's notifications to a notification channel. Each notification channel represents a type of notification, and you can group several notifications in each channel.

check the device's SDK version before building the notification channel.

When you create a notification channel in your code, you set behavior for that channel, and the behavior is applied to all of the notifications in the channel. For example, your app might set the notifications in a channel to play a sound, blink a light, or vibrate. Whatever behavior you set for a notification channel, the user can change it, and they can turn off notifications from your app altogether.

Creating Notification channels

To create a notification channel instance, use the NotificationChannel constructor. Specify an ID that's unique within your package, a user-visible channel name, and an importance for the channel:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel notificationChannel = 
         new NotificationChannel(CHANNEL_ID, "Mascot Notification",
         NotificationManager.IMPORTANCE_DEFAULT);
}

Set the importance level

The NotificationChannel constructor, which is available in Android 8.0 (API level 26) and higher, requires an importance level

To support Android 7.1 (API level 25) or lower, you must also set a priority for each notification. To set a priority, use the setPriority() method with a priority constant from the NotificationCompat class.

mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);

Configure the initial settings

notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("Notification from Mascot");

Creating notifications

You create a notification using the NotificationCompat.Builder class.

To create a NotificationCompat.Builder, pass the application context and notification channel ID to the constructor:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);

Set notification contents

 new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.android_icon)
        .setContentTitle("You've been notified!")
        .setContentText("This is your notification text.");

Set the intent for the notification's tap action

To launch an Activity in your app, set a content intent using the setContentIntent() method, passing in the Intent wrapped in a PendingIntent object. When your app uses a PendingIntent, the system can launch the Activity in your app on your behalf.

To instantiate a PendingIntent, use one of the following methods, depending on how you want the contained Intent to be delivered:

  • To launch an Activity when a user taps the notification, use PendingIntent.getActivity(). Pass in an explicit Intent for the Activity you want to launch. The getActivity() method corresponds to an Intent delivered using startActivity().
  • For an Intent passed into startService(), for example a service to download a file, use PendingIntent.getService().
  • For a broadcast Intent delivered with sendBroadcast(), use PendingIntent.getBroadcast().

The following snippet shows how to create a basic Intent to open an Activity when the user taps the notification:

// Create an explicit intent for an Activity in your app
Intent contentIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingContentIntent = PendingIntent.getActivity(this, 0,  
                         contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);                
// Set the intent that will fire when the user taps the notification
mBuilder.setContentIntent(pendingContentIntent);         

Add notification action buttons

Notification action buttons allow the user to perform an app-related task without launching the app. The system typically displays action buttons adjacent to the notification content. A notification can have up to three notification action buttons.

The following code shows how to add an action button using the addAction() method with the NotificationCompat.Builder object, passing in the icon, the title string for the label, and the PendingIntent to trigger when the user taps the action button.

mBuilder.addAction(R.drawable.car, "Get Directions", mapPendingIntent);

Expandable notifications

To create notifications that appear in an expanded layout, use one of these helper classes to set the style object to the setStyle() method:

  • Use NotificationCompat.BigTextStyle for large-format notifications that include a lot of text.
  • Use NotificationCompat.InboxStyle for displaying a list of summary lines, for example for incoming messages or emails.
  • Use NotificationCompat.MediaStyle for media playback notifications.
  • Use NotificationCompat.MessagingStyle to display sequential messages in an ongoing conversation. This style currently applies only on devices running Android 7.0 and higher. On lower devices, these notifications are displayed in the supported style.
  • Use NotificationCompat.BigPictureStyle for large-format notifications that include large image attachments, as shown in the screenshot below.

For example, here's how you'd set the BigPictureStyle on a notification:

 NotificationCompat notif = new NotificationCompat.Builder(mContext, channelId)
     .setContentTitle("New photo from " + sender.toString())
     .setContentText(subject)
     .setSmallIcon(R.drawable.new_post)
     .setLargeIcon(aBitmap)
     .setStyle(new NotificationCompat.BigPictureStyle()
         .bigPicture(aBigBitmap)
         .setBigContentTitle("Large Notification Title"))
  .build();

Ongoing notifications

Ongoing notifications are notifications that the user can't dismiss.

To make a notification ongoing, set setOngoing() to true.

Your app must explicitly cancel ongoing notifications by calling cancel() or cancelAll().

Clearing notifications

Notifications remain visible until one of the following happens:

  • If the notification can be cleared, it disappears when the user dismisses it by swiping it or by using "Clear All".
  • If you called setAutoCancel() when you created the notification, the notification cancels itself automatically. When the user taps the notification, the notification is removed from the status bar.
  • If you call cancel() on the Notification object for a specific notification ID, the notification is removed from the status bar.
  • If you call cancelAll() on the Notification object, all the notifications you've issued are removed from the status bar.

Because the user can't cancel ongoing notifications, your app must cancel them by calling cancel() or cancelAll() on the Notification object.

Delivering notifications

Use the NotificationManager class to deliver notifications:

  • To create an instance of NotificationManager, call getSystemService(), passing in the NOTIFICATION_SERVICE constant.
  • To deliver the notification, call notify().

Updating and reusing notifications

Sometimes you need to issue a notification multiple times for the same type of event. In this situation, you can update a previous notification by changing some of the notification's values, adding to the notification, or both.

To reuse an existing notification:

  1. Update a NotificationCompat.Builder object and build a Notification object from it, as when you first created and built the notification.
  2. Deliver the notification with the same ID you used previously.
package mohammad.samandari.notifyme;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.renderscript.RenderScript;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private static final String CHANNEL_ID = "channel_id_lord_notification";
private static final String TAG = "Lord";
NotificationManager mNotifyManager;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Cheaking the Android version and creating a Notification Channel
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, "Lord Notification", NotificationManager.IMPORTANCE_DEFAULT);
//Configuration of the notification channel
notificationChannel.enableLights(true);
notificationChannel.enableVibration(true);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.setDescription("Notification From Lord");
//Passing the notification channel to the notification manager
mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyManager.createNotificationChannel(notificationChannel);
}
}
public void notifyMe (View view) {
//Set the intent for the notification's tap action
// Create an explicit intent for an Activity in your app
Intent contentIntent = new Intent(this, MainActivity.class);
PendingIntent pendingContentIntent = PendingIntent.getActivity(this, 0, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
mBuilder.setContentText("This is a notification");
mBuilder.setContentTitle("Lord Notification");
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
// Set the intent that will fire when the user taps the notification
mBuilder.setContentIntent(pendingContentIntent);
//Changing the notification style to expanded mode
mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.unnamed));
mBuilder.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(BitmapFactory.decodeResource(getResources(), R.drawable.unnamed))
.setBigContentTitle("This is Big Notification"));
// mBuilder.setStyle((new NotificationCompat.InboxStyle()));
// mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(
// "dasjkldhsajklhdjklashdjklashdkjhasdkjlhasjlkdhlksjhdlksajhlkdjas"
// ));
//Add notification action buttons
mBuilder.addAction(R.drawable.ic_launcher_background, "Reply", pendingContentIntent);
mBuilder.addAction(R.drawable.ic_launcher_background, "Dismiss", pendingContentIntent);
mBuilder.addAction(R.drawable.ic_launcher_background, "New", pendingContentIntent);
//Ongoing Notification
mBuilder.setOngoing(true);
//Declaring the priority of the notification ( needed for sdk < 21 )
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
//Set which notification properties will be inherited from system defaults.
mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
//the notification cancels itself automatically. When the user taps the notification
mBuilder.setAutoCancel(true);
mNotifyManager.notify(0, mBuilder.build());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment