[Java] Even now! Implement Android Notification in Java (Beginner)

3 minute read

Introduction

Here is the basic usage of Android Notification. The content is simple for beginners. I would like to explain based on the sample application.

The environment of the sample application is as follows.

  • -Android Studio 4.0.1
  • MacOS 10.15.6
  • Android Virtual Device-android10.0 / 1080 x 2160

What is # Notification According to the official page, there is the following description

Notifications are messages that Android displays outside the app UI, providing users with reminders, messages from others, timely information from the app, and more. Users can tap the notification to open the app or interact directly from the notification.

Well, it’s difficult… In short, it is the one displayed on the status bar of the smartphone.

This sample app

This time I would like to create an application that “presses a button and displays a notification”. This is the application so far. If you tap the content after that, “Open app” etc. will not be implemented this time. Currently Kotlin is the mainstream for Android, but I would like to implement it in Java this time as well.

The sample app this time works as follows.

  • Press “BUTTON” on the screen
  • Icon is displayed in the status bar
  • When you lower the status bar, the notification content will be displayed.

sampleApp.png

Implementation

Now, let’s implement it. It’s just a button in the center of the screen. MainActivity.java and activity_main.xml are as follows.

activtiy_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools: context = ". MainActivity">
    
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android: layout_height = "wrap_content"
        android:text="Button"
        app: layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT> = Build.VERSION_CODES.O) {// ・ ・ ・ (1)
            int importance = NotificationManager.IMPORTANCE_DEFAULT;

            NotificationChannel channel // ...(2)
                = new NotificationChannel("CHANNEL_ID", "Sample App", importance);

            channel.setDescription ("Description / Explanation You can write a description of the notification here");
                  
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
        
        Button button = findViewById (R.id.button);
        button.setOnClickListener (v-> notifyTest ()); // ・ ・ ・ (3)
    }

    public void notifyTest () {
        NotificationCompat.Builder builder
            = new NotificationCompat.Builder(this, "CHANNEL_ID") // ・・・(4)
                .setSmallIcon(android.R.drawable.ic_menu_info_details)
                .setContentTitle("title")
                .setContentText("message message")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        NotificationManagerCompat notificationManager
                = NotificationManagerCompat.from(this);

        notificationManager.notify(R.string.app_name, builder.build());
                                                                     // ···(Five)
    }
}

(1) To deliver notifications on Android 8.0 or above, you need to register the notification channel of the app in the system. Run this code as soon as the app starts.

Creating an existing notification channel will not perform the operation, so it’s safe to call it repeatedly.

So, if you call it with onCreate, there should be no problem.

(2) Implementation of notification channel. The notification channel has the following image. It is a screen that can be seen from smartphone settings -> application / notification.

Screenshot 2020-09-05 23.30.30.png

(3) Implement the processing when the button is pressed.

(4) Create a notification. You can set icons, titles, messages, etc.

  • Set a small icon with setSmallIcon().
  • Set the title with setContentTitle ().
  • Set the body text with setContentText().
  • Set the notification priority with setPriority().

![Screenshot 2020-09-05 23.36.35.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/701083/6bccdb5b-9f82-192e-0262-(1aef682a6bb2.png)

(5) Display the notification. Display the notification with notificationManager.notify. Pass a unique ID and the result of NotificationCompat.Builder.build () as an argument.

Operation check

When you start the application and press the displayed button, a notification should be displayed. If the movement is the same as the diagram in the sample app above, you are successful!

Summary

Did the sample work safely? Maybe it will work with copy and paste. If you want to deliver notifications on Android 8.0 or later, you need to implement additional notifications, and I think that the rest is relatively easy.

Notifications have many more features. You can also add a progress bar, and add the implementation when you tap the notification. I will write about the implementation around this in the future.

see you!