Java Android App Development Course, Displaying Notifications

One of the ways to convey important information or messages to users while developing an Android app is through notifications. Notifications are important UI elements that can capture the user’s attention and encourage interaction with the app. In this tutorial, we will take a closer look at how to create and display notifications in an Android app using Java.

1. Concept of Notification

In Android, a notification is a message that is displayed on the user’s device. Notifications generally consist of the following components:

  • Title: A brief display of the subject or main content of the notification.
  • Content: Contains the details intended to be conveyed in the notification.
  • Icon: Used for the visual representation of the notification.
  • Action: Defines the action to be performed when the user clicks on the notification.

2. Components of Android Notifications

The main components that must be used to display notifications are as follows:

  • NotificationManager: A system service that manages notifications.
  • NotificationChannel: Starting from Android O (API 26) and above, notification channels must be used to group notifications and provide settings to the user.

3. Steps to Show Notifications

3.1 Project Setup

Create a new project in Android Studio. At this time, select ‘Empty Activity’ and choose either Kotlin or Java as your programming language. Here, we will explain an example using Java.

3.2 Adding Required Permissions

Special permissions are not required to display notifications, but it is advisable to guide users to allow notifications in the app’s settings. Ensure that the following basic settings are included in AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.notificationexample">

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN"/>
                    <category android:name="android.intent.category.LAUNCHER"/>
                </intent-filter>
            </activity>
        </application>
    </manifest>

3.3 Creating Notification Channel (API 26 and above)

You need to set up a NotificationChannel to create a channel through which notifications can be sent. Below is an example of creating a notification channel in the MainActivity.java file:

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;

public class MainActivity extends AppCompatActivity {
    private static final String CHANNEL_ID = "notifyExample";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        createNotificationChannel();  // Call the method to create the channel
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Example Channel";
            String description = "This is a channel for notification examples.";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}

3.4 Creating and Displaying Notifications

Now you are ready to create and display notifications. Here is an example of setting up a notification to be shown when a button is clicked.

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

public class MainActivity extends AppCompatActivity {
    private static final String CHANNEL_ID = "notifyExample";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        createNotificationChannel(); // Create notification channel

        Button button = findViewById(R.id.notify_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendNotification(); // Send notification
            }
        });
    }

    private void sendNotification() {
        Intent intent = new Intent(this, NotificationActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_notification) // Icon to display
                .setContentTitle("New Notification") // Notification title
                .setContentText("Check the message here.") // Notification content
                .setPriority(NotificationCompat.PRIORITY_DEFAULT) // Set priority
                .setContentIntent(pendingIntent) // Set intent to execute on click
                .setAutoCancel(true); // Automatically delete on click

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(1, builder.build()); // Create notification
    }
}

3.5 Handling Notification Clicks

To open a specific activity when the notification is clicked, you can handle it as follows. This involves creating and using a separate NotificationActivity class.

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class NotificationActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification); // Reference appropriate layout file
    }
}

4. Various Options for Notifications

In addition to basic messages, various options can be utilized for notifications. Here are some commonly used options:

  • Sound: You can set a sound to play when the notification is displayed.
  • Vibration: You can make the device vibrate when the notification is triggered.
  • Suppress in Status Bar: You can control whether to display the notification in the status bar.

4.1 Adding Sound

Here is a code example for adding sound to a notification:

builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI); // Use default notification sound

4.2 Adding Vibration

Here’s how to add vibration to a notification:

VibrationUtils vibration = (VibrationUtils) getSystemService(Context.VIBRATOR_SERVICE);
    vibration.vibrate(1000); // Vibrate for 1 second

5. Grouping Notifications

You can also group multiple notifications for display. This can be set up using new channels and group IDs. Here is an example code:

NotificationCompat.Builder summaryBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Grouped Notification")
            .setContentText("There are multiple notifications.")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setGroup(GROUP_KEY_WORK_EMAIL)
            .setStyle(new NotificationCompat.InboxStyle()
                .addLine("First Notification")
                .addLine("Second Notification")
                .setSummaryText("+2 more"));

    notificationManager.notify(SUMMARY_ID, summaryBuilder.build()); // Create grouped notification

6. Cancelling Notifications

If you want to cancel a notification that has been created, you can use the cancel method of NotificationManager. Here’s an example of canceling a notification:

notificationManager.cancel(1); // Cancel a specific notification using its ID

7. Conclusion

In this tutorial, we thoroughly explored how to show notifications in Android. Notifications are a very useful feature for conveying important information to users. Implementing notification features in your project can enhance the user experience. Furthermore, consider ways to group notifications or adjust various options to provide more suitable notifications for users.

Today, you’ve learned how to create and display notifications in an Android app using Java. Remember to experiment with different notification options to enhance your app’s user experience!