Showing Notifications in Android Java

In this tutorial, we will create a notification generator application in Android using Java.
You can use any latest version of Android Studio. This tutorial was written using Android Studio 4.1.

Setting up new project

First, create a new Project:

  1. Open Android Studio and click on the file option on the upper left corner of the screen.
  2. Click on the new option and select the wizard that you want and click on the next option.
  3. Now enter the details that are the name of the project(Codespeedy), name of the package(org.codespeedy), and android version(26).
  4. Click on the finish option. (You will get two files MainActivity.java and activity_main.xml)

Code

Foreground permission is required when your app needs to perform a task that is noticeable by the user even when they’re not directly interacting with the app.
WakeLock permission is required to do things even when the device seems to be asleep

So, add these two permissions in the manifest.xml file:

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

Like This:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.codespeedy">

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

    <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.CodeSpeedy">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".BroadcastReceiver.NotificationReminderBroadcast" />

    </application>

</manifest>

Now, create two new packages with names BroadcastReceiver and utils inside the working directory like this:

In the NotificationReminderBroadcast.java file we write the code that actually produces the notification:

package org.codespeedy.BroadcastReceiver;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.core.app.NotificationCompat;
import org.codespeedy.MainActivity;
import org.codespeedy.R;
import org.codespeedy.utils.Global;

public class NotificationReminderBroadcast extends BroadcastReceiver {

    private NotificationManager mNotificationManager;

    // Notification ID.
    private static final int NOTIFICATION_ID = 0;

    // Notification channel ID.
    private static final String PRIMARY_CHANNEL_ID = "your_notification_channel_id";

    @Override
    public void onReceive(Context context, Intent intent) {

        mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        // Create the content intent for the notification, which launches
        // this activity
        Intent contentIntent = new Intent(context, MainActivity.class);

        PendingIntent contentPendingIntent = PendingIntent.getActivity
                (context, NOTIFICATION_ID, contentIntent, PendingIntent
                        .FLAG_UPDATE_CURRENT);

        String title = Global.getInstance().getTitle();
        String content = Global.getInstance().getContent();

        // Build the notification
        NotificationCompat.Builder builder = new NotificationCompat.Builder
                (context, PRIMARY_CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle(title)
                .setContentText(content)
                .setContentIntent(contentPendingIntent)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true)
                .setDefaults(NotificationCompat.DEFAULT_ALL);

        // Deliver the notification
        mNotificationManager.notify(NOTIFICATION_ID, builder.build());
    }

}

In the above code, we have created a broadcast receiver within which we first get the NOTIFICATION_SERVICE, then a pending intent is created with a notification_id and a contentIntent.

Then there’s the code for building the actual notification from line 41, where we specify the title and content of the notification.

Then we notify the notification manager (Notification Service) about this notification.

Now in the Global.java (util package) file we write this below code to make it easy for us to generate notification with our chosen title and content:

our chosen name and content:
package org.codespeedy.utils;

public class Global {

    private String email ;
    private String password ;

    private String title="Not Set";
    private String content="Not Set";

    private static Global instance;

    // Getter/setter

    public static Global getInstance() {
        if (instance == null)
            instance = new Global();
        return instance;
    }

    private Global() {
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

This file is used to create a global scope object to store and fetch data across files.

Now inside the NotificationUtil.java file we write the code that will create channel and the one that will send a message to our NotificationReminderBroadcast after some time to generate the notification.
Code of this file:

package org.codespeedy.utils;

import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;

import org.codespeedy.BroadcastReceiver.NotificationReminderBroadcast;

public class NotificationUtil {

    public static void setNotification(Context context, String title, String content, long delay) {
        Global.getInstance().setContent(content);
        Global.getInstance().setTitle(title);

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(context, NotificationReminderBroadcast.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

                AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delay, pendingIntent);
            }
        }, 2000);
    }

    public static void createChannel(Context context,String channel_id) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "CodeSpeedy";
            String description = "Channel for Reminder";
            int importance = NotificationManager.IMPORTANCE_HIGH;

            NotificationChannel channel = new NotificationChannel(channel_id, name, importance);
            channel.setDescription(description);
            channel.enableVibration(true);

            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}

Here there’s a a create a channel function because its required by Android OS versions >= Oreo version.
Then there’s setNotification() function which calls the NotificationReminderBroadcast that we had created to create our notification after a certain delay (specified by us) using the AlarmManager.
Above written code is basically like an API overĀ  NotificationReminderBroadcast.java file to make our work easier.

Now after having written a lot of code, we can make any notification by one single line:
MainActivity.java File Code:

package org.codespeedy;

import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import org.codespeedy.utils.NotificationUtil;

public class MainActivity extends AppCompatActivity {

    Button mSetNotificationButton;

    @Override
    public void onCreate(Bundle saved) {
        super.onCreate(saved);
        setContentView(R.layout.activity_main);

        mSetNotificationButton = findViewById(R.id.set_notification_button);

        NotificationUtil.createChannel(this,"your_notification_channel_id");

        mSetNotificationButton.setOnClickListener(v->{
            NotificationUtil.setNotification(this,"Notification From CodeSpeedy","CodeSpeedy App",200);
        });
    }
}

Now run the app on your mobile using USB debugging cable(recommended), and click on the SET NOTIFICATION button when the app opens up, and then wait for few seconds.

Android Notification

Leave a Reply

Your email address will not be published. Required fields are marked *