Paramclasses Academy - Blog

Tutorials Details

←
Post 31 of 40
→

How to Create Notifications in Android Studio Using Java ?

How to Create Notifications in Android Studio Using Java ?

November 4, 2026

Introduction

Notifications are an important feature of Android applications. They allow apps to display alerts, reminders, messages, updates, and other useful information even when the application is not currently open.

For example:

  • WhatsApp displays notifications when new messages arrive.

  • Shopping applications notify users about orders and offers.

  • Banking applications send transaction alerts.

  • Calendar applications display event reminders.

  • News applications notify users about breaking news.

Android provides notification APIs that developers can use to create and display notifications.

In this tutorial, we will learn how to create Android notifications using Java and Android Studio.

By the end of this tutorial, you will build a Notification Demo App that can:

  • Create a notification channel.

  • Request notification permission.

  • Display a notification when a button is clicked.

  • Show a notification title and message.

  • Open the application when the user taps the notification.

1. What Is a Notification in Android?

A notification is a message displayed by Android outside the application's normal user interface.

Notifications usually appear in the notification shade, which users can open by swiping down from the top of the screen.

A notification can contain:

  • Small application icon.

  • Notification title.

  • Notification message.

  • Timestamp.

  • Optional action buttons.

  • Additional expanded content.

Notifications help applications communicate important information to users without requiring them to open the application manually.

2. Understanding Important Notification Components

Before writing code, understand these important Android notification components.

NotificationCompat.Builder

NotificationCompat.Builder is used to configure notification content and appearance.

It allows developers to set:

  • Notification title.

  • Notification message.

  • Small icon.

  • Priority.

  • Tap action.

  • Expanded notification style.

Notification Channel

A notification channel groups notifications by category.

For example, a messaging application might create separate channels for:

  • Messages.

  • Group messages.

  • Reminders.

  • Promotions.

Notification channels are required for applications running on Android 8.0 (API level 26) and higher.

Users can manage channel settings through Android system settings.

NotificationManagerCompat

NotificationManagerCompat is used to send notifications to the Android system.

We will use its notify() method to display our notification.

PendingIntent

A PendingIntent allows the Android system to perform an action on behalf of the application at a later time.

For example, when a user taps a notification, a PendingIntent can open the application's MainActivity.

3. Create a New Android Studio Project

First, open Android Studio.

Follow these steps:

  1. Click New Project.

  2. Select Empty Views Activity.

  3. Enter the project name: NotificationDemoApp.

  4. Select Java as the programming language.

  5. Choose a suitable minimum SDK.

  6. Click Finish.

Wait for Gradle Sync to complete.

We will use these files:

  • MainActivity.java

  • activity_main.xml

  • AndroidManifest.xml

4. Add the Required Dependency

We will use AndroidX Core's NotificationCompat and NotificationManagerCompat classes.

Open the module-level build.gradle file and add:

implementation 'androidx.core:core:1.15.0'

For Kotlin DSL, use:

implementation("androidx.core:core:1.15.0")

If AndroidX Core is already available through your project's dependencies, you do not need to add it again.

Click Sync Now.

5. Add Notification Permission

Android 13 (API level 33) introduced a runtime permission for displaying regular notifications.

Open AndroidManifest.xml and add this permission above the application element:

<uses-permission
    android:name="android.permission.POST_NOTIFICATIONS" />

This permission is required for applications targeting Android 13 or higher to request permission to send non-exempt notifications.

On Android 12 and earlier, this runtime permission is not required.

We will request the permission at runtime on Android 13 and later.

6. Design the Application Layout

Now create a simple user interface with a title, description, and button.

Open activity_main.xml and replace its content with:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="24dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Notification Demo App"
        android:textSize="24sp"
        android:textStyle="bold"
        android:gravity="center"
        android:padding="12dp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click the button below to display a notification."
        android:textSize="16sp"
        android:gravity="center"
        android:padding="12dp" />

    <Button
        android:id="@+id/btnShowNotification"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Notification" />

</LinearLayout>

Understanding the XML Components

LinearLayout: Arranges the user interface components vertically.

TextView: Displays the application title and description.

Button: Allows the user to trigger a notification.

We will handle the button click inside MainActivity.java.

7. Create a Notification Channel

Android 8.0 and later require notification channels.

We will create a channel named General Notifications.

Add this method inside MainActivity.java:

private static final String CHANNEL_ID = "general_notifications";

private void createNotificationChannel() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        CharSequence name = "General Notifications";

        String description = "General app notifications";

        int importance = NotificationManager.IMPORTANCE_DEFAULT;

        NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                name,
                importance
        );

        channel.setDescription(description);

        NotificationManager notificationManager =
                getSystemService(NotificationManager.class);

        notificationManager.createNotificationChannel(channel);
    }
}

Understanding the Code

CHANNEL_ID: Uniquely identifies the notification channel.

NotificationChannel: Creates a new notification category.

IMPORTANCE_DEFAULT: Sets the channel's default notification importance.

setDescription(): Adds a description to the channel.

createNotificationChannel(): Registers the channel with Android.

You should create the channel before sending notifications. Calling this method repeatedly with the same channel ID is safe; Android does not recreate an existing channel from scratch.

8. Request Notification Permission

Now we will implement runtime notification permission.

Android 13 and later require the POST_NOTIFICATIONS permission for regular notifications.

Add this permission launcher inside your MainActivity class:

private final ActivityResultLauncher<String> requestPermissionLauncher =
        registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                isGranted -> {

                    if (isGranted) {
                        showNotification();
                    } else {
                        Toast.makeText(
                                this,
                                "Notification permission denied",
                                Toast.LENGTH_SHORT
                        ).show();
                    }
                }
        );

Now create a method to check the permission:

private void checkNotificationPermission() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {

        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.POST_NOTIFICATIONS
        ) == PackageManager.PERMISSION_GRANTED) {

            showNotification();

        } else {

            requestPermissionLauncher.launch(
                    Manifest.permission.POST_NOTIFICATIONS
            );
        }

    } else {

        showNotification();
    }
}

Understanding the Code

ActivityResultLauncher: Launches a permission request and receives its result.

POST_NOTIFICATIONS: The Android 13+ runtime notification permission.

ContextCompat.checkSelfPermission(): Checks whether the permission has already been granted.

requestPermissionLauncher.launch(): Displays the system permission dialog.

If the user grants permission, the application displays the notification. If permission is denied, the application shows a message instead.

9. Create and Display a Notification

Now we will create the main notification method.

Add this method inside MainActivity.java:

private void showNotification() {

    Intent intent = new Intent(
            MainActivity.this,
            MainActivity.class
    );

    PendingIntent pendingIntent = PendingIntent.getActivity(
            this,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT |
                    PendingIntent.FLAG_IMMUTABLE
    );

    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this, CHANNEL_ID)

                    .setSmallIcon(android.R.drawable.ic_dialog_info)

                    .setContentTitle("New Notification")

                    .setContentText(
                            "Hello! Your Android notification is working."
                    )

                    .setPriority(
                            NotificationCompat.PRIORITY_DEFAULT
                    )

                    .setContentIntent(pendingIntent)

                    .setAutoCancel(true);

    NotificationManagerCompat notificationManager =
            NotificationManagerCompat.from(this);

    try {

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

    } catch (SecurityException e) {

        Toast.makeText(
                this,
                "Notification permission is required",
                Toast.LENGTH_SHORT
        ).show();
    }
}

Understanding the Important Methods

Intent

Intent intent = new Intent(
        MainActivity.this,
        MainActivity.class
);

Creates an intent that points to the application's MainActivity.

PendingIntent

PendingIntent pendingIntent = PendingIntent.getActivity(
        this,
        0,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT |
                PendingIntent.FLAG_IMMUTABLE
);

Creates a PendingIntent that allows the Android system to open MainActivity when the notification is tapped.

setSmallIcon()

.setSmallIcon(android.R.drawable.ic_dialog_info)

Sets the small notification icon.

A production application should use its own notification icon resource.

setContentTitle()

.setContentTitle("New Notification")

Sets the notification title.

setContentText()

.setContentText("Hello! Your Android notification is working.")

Sets the notification message.

setPriority()

.setPriority(NotificationCompat.PRIORITY_DEFAULT)

Sets the notification priority for older Android versions. On Android 8.0 and later, the notification channel's importance controls the behavior.

setAutoCancel()

.setAutoCancel(true)

Automatically removes the notification from the notification shade after the user taps it.

notify()

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

Sends the notification to the Android system.

The number 101 is the notification ID. You can use this ID later to update or cancel the notification.

10. Complete MainActivity.java Code

Now combine the methods into one complete Java file.

Open MainActivity.java and use the following code:

package com.example.notificationdemoapp;

import android.Manifest;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

    private static final String CHANNEL_ID =
            "general_notifications";

    private Button btnShowNotification;

    private final ActivityResultLauncher<String> requestPermissionLauncher =
            registerForActivityResult(
                    new ActivityResultContracts.RequestPermission(),
                    isGranted -> {

                        if (isGranted) {
                            showNotification();
                        } else {
                            Toast.makeText(
                                    this,
                                    "Notification permission denied",
                                    Toast.LENGTH_SHORT
                            ).show();
                        }
                    }
            );

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        btnShowNotification =
                findViewById(R.id.btnShowNotification);

        createNotificationChannel();

        btnShowNotification.setOnClickListener(v ->
                checkNotificationPermission()
        );
    }

    private void createNotificationChannel() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            CharSequence name = "General Notifications";

            String description =
                    "General app notifications";

            int importance =
                    NotificationManager.IMPORTANCE_DEFAULT;

            NotificationChannel channel =
                    new NotificationChannel(
                            CHANNEL_ID,
                            name,
                            importance
                    );

            channel.setDescription(description);

            NotificationManager notificationManager =
                    getSystemService(NotificationManager.class);

            notificationManager.createNotificationChannel(channel);
        }
    }

    private void checkNotificationPermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {

            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.POST_NOTIFICATIONS
            ) == PackageManager.PERMISSION_GRANTED) {

                showNotification();

            } else {

                requestPermissionLauncher.launch(
                        Manifest.permission.POST_NOTIFICATIONS
                );
            }

        } else {

            showNotification();
        }
    }

    private void showNotification() {

        Intent intent = new Intent(
                MainActivity.this,
                MainActivity.class
        );

        PendingIntent pendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        intent,
                        PendingIntent.FLAG_UPDATE_CURRENT |
                                PendingIntent.FLAG_IMMUTABLE
                );

        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(
                        this,
                        CHANNEL_ID
                )

                .setSmallIcon(
                        android.R.drawable.ic_dialog_info
                )

                .setContentTitle("New Notification")

                .setContentText(
                        "Hello! Your Android notification is working."
                )

                .setPriority(
                        NotificationCompat.PRIORITY_DEFAULT
                )

                .setContentIntent(pendingIntent)

                .setAutoCancel(true);

        NotificationManagerCompat notificationManager =
                NotificationManagerCompat.from(this);

        try {

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

        } catch (SecurityException e) {

            Toast.makeText(
                    this,
                    "Notification permission is required",
                    Toast.LENGTH_SHORT
            ).show();
        }
    }
}

Important: Replace the package declaration with your actual Android project's package name. Keep the existing project plugins and dependencies.

11. Run and Test the Application

Now run the application on an Android emulator or a real Android device.

Follow these steps:

  1. Open the Notification Demo App.

  2. Click the Show Notification button.

  3. On Android 13 or later, the notification permission dialog appears if permission has not already been granted.

  4. Select Allow.

  5. The application creates and displays a notification.

  6. Swipe down from the top of the screen to open the notification shade.

  7. Find the notification titled New Notification.

  8. Tap the notification to open MainActivity.

On Android 12 and earlier, the runtime notification permission dialog is not required by this example.

12. How to Cancel a Notification

Android also allows developers to cancel notifications.

Use the following code:

NotificationManagerCompat notificationManager =
        NotificationManagerCompat.from(this);

notificationManager.cancel(101);

The cancel() method removes the notification with ID 101.

You can also cancel all notifications sent by your application:

notificationManager.cancelAll();

13. Common Notification Errors and Solutions

Error 1: Notification Is Not Displaying

Possible reasons:

  • Notification permission has not been granted.

  • The user has disabled notifications in system settings.

  • The notification channel is disabled.

  • The application is using an incorrect channel ID.

Solution: Check notification permission and channel settings.

Error 2: Notification Channel Not Found

Possible reason: The notification is being sent before its channel has been created.

Solution: Call createNotificationChannel() before sending notifications.

Error 3: Notification Permission Denied

Possible reason: The user selected Don't allow.

Solution: Explain the purpose of notifications and provide a way to open the application's notification settings if the user wants to enable them.

Error 4: PendingIntent Error

Possible reason: The PendingIntent flags are missing or incorrectly configured.

Solution: Use appropriate flags such as FLAG_UPDATE_CURRENT and FLAG_IMMUTABLE for this example.

14. Best Practices for Android Notifications

Follow these practices when developing production Android applications:

  • Display notifications only when they provide useful information.

  • Request notification permission at an appropriate time.

  • Create separate channels for different notification categories.

  • Use meaningful notification titles and messages.

  • Use a proper small notification icon.

  • Make notification tap actions useful.

  • Avoid sending duplicate or unnecessary notifications.

  • Respect the user's notification preferences.

  • Do not expose sensitive information in notification previews.

Conclusion

In this tutorial, we learned how to create and manage notifications in Android Studio using Java.

We covered NotificationCompat, NotificationChannel, NotificationManagerCompat, PendingIntent, runtime notification permission, and notification cancellation.

We also created a practical Notification Demo App that displays a notification when the user clicks a button.

These concepts are useful for building messaging applications, shopping applications, reminder apps, banking applications, and other Android projects.

Frequently Asked Questions

1. What is a notification in Android?

A notification is a message displayed by Android to inform users about important updates, messages, reminders, or events.

2. What is NotificationChannel?

NotificationChannel is used to group notifications into categories and allows users to control their notification settings.

3. What is NotificationCompat?

NotificationCompat is an AndroidX library class that helps developers create notifications with compatibility across Android versions.

4. What is PendingIntent?

PendingIntent allows the Android system to execute a predefined action on behalf of an application, such as opening an Activity when a notification is tapped.

5. Is notification permission required in Android 13?

Yes. Android 13 (API level 33) introduced the POST_NOTIFICATIONS runtime permission for regular notifications.

6. How can we cancel a notification in Android?

Use NotificationManagerCompat.cancel(notificationId) to remove a specific notification.

7. Can Android applications display notifications when they are closed?

Yes. Notifications can be displayed when an application is not open, provided the notification is triggered by an appropriate mechanism and the required permissions and system conditions are satisfied.

←
Post 31 of 40
→