Programming Tips - Android: display a notification

Date: 2020sep12 OS: Android Language: Java Q. Android: display a notification A. It has envolved over the years. But this worked for me in 2020.
public class MyApp extends Application { private int mNotificationId = 1; private String mNotificationChannelIdCache; private String getAppName() { return "My App Name"; } private String getNotificationChannelId() { if (mNotificationChannelIdCache != null) return mNotificationChannelIdCache; mNotificationChannelIdCache = getPackageName(); return mNotificationChannelIdCache; } private void createNotificationChannel() { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { final CharSequence name = getString(R.string.channel_name); final String description = getString(R.string.channel_description); final int importance = NotificationManager.IMPORTANCE_DEFAULT; final NotificationChannel channel = new NotificationChannel(getNotificationChannelId(), name, importance); channel.setDescription(description); // Register the channel with the system; you can't change the importance // or other notification behaviors after this NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } } public void notify(final String msg) { Intent resultIntent = new Intent(this, MainActivity.class); PendingIntent resultPendingIntent = PendingIntent.getActivity( this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT ); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, getNotificationChannelId()) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(getAppName()) .setContentText(msg) .setContentIntent(resultPendingIntent) .setPriority(NotificationCompat.PRIORITY_DEFAULT); // Sets an ID for the notification // Gets an instance of the NotificationManager service NotificationManager notifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notifyMgr.notify(mNotificationId++,; } void exampleUse() { notify("Hello"); }