Function and usage of Notification

Notification is a notification displayed in the status bar of the mobile phone - the status bar is located at the top of the mobile phone screen, where the current network status, battery status, time, etc. of the mobile phone are generally displayed. Notification represents a kind of notification with global effect. The program usually sends notification through the notification manager service.
Android adds a Notification.Builder class for notification, which allows developers to create notification objects more easily. Notification.Builder provides the following common methods.

  • setDefaults(): set notification LED, music, vibration, etc.
  • Setautoconcel(): set to automatically delete the notification in the status bar after clicking the notification.
  • setContentTitle(): set notification title.
  • setContentText(): set notification content.
  • setSmallIcon(): sets the icon for notifications.
  • setLargeIcon(): sets a large icon for notifications.
  • setTick(): sets the prompt text of the notification bar in the status bar.
  • setContentIntent(): set the pendingintent corresponding to the program component to be started after clicking the notification.

Sending Notification is very simple, just follow the steps below.

  1. Call the getsystemservice (notification? Service) method to get the notification manager service of the system.
  2. Create a Notification object through the constructor.
  3. Set various properties for Notification.
  4. Send Notification through the Notification () method of Notification manager

Version number if greater than or equal to 8.0

To create a notification, there are several steps:

  1. There are three parameters for constructing NotificationChannel object: channel id, channel name, and channel importance level.
  2. Call the NotificationChannel.setDescription method to set the channel description. This description can be seen in the system settings.
  3. Call the NotificationManager.createNotificationChannel method to create a notification channel
  4. Set various properties for Notification.
  5. Send Notification through the Notification () method of Notification manager

Here is the code of the registration notification channel

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    //Create notification channels
    CharSequence name = "Channel name 1";
    String description = "Channel description 1";
    String channelId="channelId1";//Channel id     
    int importance = NotificationManager.IMPORTANCE_DEFAULT;//Importance level
    NotificationChannel mChannel = new NotificationChannel(channelId, name, importance);
    mChannel.setDescription(description);//Channel description
    mChannel.enableLights(true);//Display notification indicator
    mChannel.enableVibration(true);//Whether vibration

    NotificationManager notificationManager = (NotificationManager) getSystemService(
            NOTIFICATION_SERVICE);
    notificationManager.createNotificationChannel(mChannel);//Create notification channels
}
Example: salary increase notice

java code

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

public class Main2Activity extends Activity {
    static final int NOTIFICATION_ID = 0X123;
    NotificationManager nm;
    String id = "jia";
    String title = "A pay notice";
    Notification notification;
    NotificationCompat.Builder builder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        //Get the notification manager service of the system
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    }
    //Define the event handling method for the click event of the button to send the notification
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void send(View view) {
        //Create an Intent to start other activities
        Intent intent = new Intent(Main2Activity.this,MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = nm.getNotificationChannel(id);
            if (mChannel == null) {
                mChannel = new NotificationChannel(id, title, importance);
                mChannel.enableVibration(true);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});//Vibration mode
                nm.createNotificationChannel(mChannel);
            }
            builder = new NotificationCompat.Builder(this,id);
            builder.setAutoCancel(true)
                    .setContentTitle("A pay notice")
                    .setSmallIcon(R.drawable.before_nh)
                    .setContentText("Salary increase 10%")
                    .setContentIntent(pi)
                    .setWhen(System.currentTimeMillis())
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.after_nh));
        }else{
            builder = new NotificationCompat.Builder(this);
            builder.setAutoCancel(true)
                    .setContentTitle("A pay notice")
                    .setSmallIcon(R.drawable.before_nh)
                    .setContentText("Salary increase 10%")
                    .setContentIntent(pi)
                    .setWhen(System.currentTimeMillis())
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.after_nh));
        }
        notification = builder.build();
        nm.notify(NOTIFICATION_ID,notification);

    }

    public void del(View view) {
    	nm.cancel(NOTIFICATION_ID);
    }
}

Layout file

<?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=".Main2Activity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sending notice"
        android:onClick="send"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/guideline"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cancellation notice"
        android:onClick="del"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>

NotificationChanne

Android Developer documentation
Construction method:
NotificationChannel(String id, CharSequence name, int importance)

Parameters in construction method

Parameter name Explain
id String: ID of the channel. Each package must be unique. If the value is too long, it may be truncated
name CharSequence: the user visible name of the channel. When the system locale changes, you can rename the channel by listening to the intent ා action ﹐ local ﹐ changed broadcast. The recommended maximum length is 40 characters; if the value is too long, it may be truncated.
importance int: the importance of channels. This controls how interrupt notifications are sent to this channel. The value is notificationmanager.import? Unspecified
NotificationManager.IMPORTANCE_NONE
NotificationManager.IMPORTANCE_MIN
NotificationManager.IMPORTANCE_LOW
NotificationManager.IMPORTANCE_DEFAULT
Or notificationmanager.import "high

Public method:
boolean canBubble()
Returns whether notifications published to this channel can be displayed outside the notification shadow in the floating window at the top of other apps.

boolean canBypassDnd()
Whether notifications published to this channel can bypass the do not disturb notification manager? Interruption? Filter? Priority mode.

boolean canShowBadge()
Returns whether notifications published to this channel can be displayed as badges in the initiator application.

int describeContents()
Describes the kind of special objects contained in the group representation of this Parcelable instance.

void enableLights(boolean lights)
Set whether notifications published to this channel should display a notification light on devices that support this feature.

void enableVibration(boolean vibration)
Set whether notifications published to this channel should vibrate.

boolean equals(Object o)
Indicates whether another object is "equal" to this object.

AudioAttributes getAudioAttributes()
Returns the audio properties of a sound played by a notification published to this channel.

String getDescription()
Returns the user visible description of this channel.

String getGroup()
Returns the group to which this channel belongs.

String getId()
Returns the ID of this channel.

int getImportance()
Returns the importance specified by the user, for example

int getLightColor()
Returns the notification light color for notifications posted to this channel.

int getLockscreenVisibility()
Returns whether notifications published to this channel are displayed on the lock screen in full or edited form.

CharSequence getName()
Returns the user visible name of this channel.

Uri getSound()
Returns the notification sound for this channel.

long[] getVibrationPattern()
Returns the vibration mode of the notification published to this channel.

boolean hasUserSetImportance()
Returns whether the user chooses the importance of the channel, confirms the initial selection from the application, or changes it to higher or lower.

int hashCode()
Returns the hash code value of the object.

void setAllowBubbles(boolean allowBubbles)
Sets whether notifications published to this channel can be displayed outside the notification bar, floating as bubbles over the content of other applications.

void setBypassDnd(boolean bypassDnd)
Sets whether notifications published to this channel can interrupt users in notificationmanager.interruption? Filter? Priority mode.

void setDescription(String description)
Set the user visible description for this channel.

void setGroup(String groupId)
Set the group to which this channel belongs.

void setImportance(int importance)
Set the interrupt level for this notification channel.

void setLightColor(int argb)
If there is an LED enabled on this channel and the device supports this function, set the notification light color for notifications published to this channel.

void setLockscreenVisibility(int lockscreenVisibility)
Sets whether notifications published to this channel are displayed on the lock screen or, if so, in the form of abridgements.

void setName(CharSequence name)
Set the user visible name for this channel.

void setShowBadge(boolean showBadge)
Sets whether notifications published to this channel can be displayed as application icon flags in the initiator.

void setSound(Uri sound, AudioAttributes audioAttributes)
Set the sound and its audio properties that notifications published to this channel should play.

void setVibrationPattern(long[] vibrationPattern)
Set the vibration mode for notifications published to this channel.

boolean shouldShowLights()
Returns whether notifications published to this channel trigger a notification light.

boolean shouldVibrate()
Returns whether notifications published to this channel are always vibrating.

String toString()
Returns the string representation of the object.

void writeToParcel(Parcel dest, int flags)
Flatten this object into the wrap.

Published 1 original article, praised 0, visited 15
Private letter follow

Tags: Android Mobile network Java

Posted on Sun, 19 Jan 2020 00:15:26 -0500 by salmanshafiq