Android Notification Java Example

Notifications provide short, timely information about events in your app while it's not in use
A notification is a message that Android displays outside your app's UI to provide the user with reminders, communication from other people, or other timely information from your app. Users can tap the notification to open your app or take an action directly from the notification.

Notification Anatomy



The most common parts of a notification are indicated above diagram as follows:
  1. SmallIcon :   This is set by calling setSmallIcon() .
  2. App Name :  This is by default provided by system .
  3. Time :  This is by default provided by system , It can be overridden by calline setWhen() or hide by calling setShowWhen(false) .
  4. Title :  This is set by calling setContentTitle() .
  5. Content :  This is set by calling setContentText() .
  6. LargeIcon :  This is set by calling setLargeIcon() .

 NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(getApplicationContext(), channedId)
                        .setSmallIcon(R.drawable.ic_notifications_active)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                        .setAutoCancel(true)
                        .setLights(Color.BLUE, 500, 500)
                        .setVibrate(new long[]{500, 500, 500})
                        .setPriority(priorty)
                        .setContentTitle(title)
                        .setContentText(content)

Setting Pending Intent to Notification


 A PendingIntent is a token that you give to a foreign application which allows the foreign application to use your application's permissions to execute a predefined piece of code.

Create an explicit intent 
Intent intent = new Intent(this, NotifyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Bundle extras = new Bundle();
extras.putString(NotifyActivity.notify_title, title);
extras.putString(NotifyActivity.notify_content, content);
intent.putExtras(extras);
intent.setAction(Intent.ACTION_VIEW);


A pending intent is a wrapper around regular intent that is designed to be used by another application. 
 PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), notificationID, intent,
			PendingIntent.FLAG_UPDATE_CURRENT);

and then set the pending to your notification builder 
 NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(getApplicationContext(), channedId)
				.setContentIntent(pendingIntent)

Notification Channel

  • Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear.
  • Categorizing notifications into channels User can disable notification for particular category instead of all 
// Since android Oreo notification channel is needed.
	NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MainActivity.this);

	// Since android Oreo notification channel is needed.
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
		NotificationChannel channel = new NotificationChannel(channedId,
				channedId,
				NotificationManager.IMPORTANCE_HIGH);
		channel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
		notificationManager.createNotificationChannel(channel);
	}



Notification importance


The possible importance levels are the following:
  1. Urgent: Makes a sound and appears as a heads-up notification.
  2. High: Makes a sound.
  3. Medium: No sound.
  4. Low: No sound and does not appear in the status bar. 

Play Notification Sound


 public void playNotificationSound() {
	try {
		Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		Ringtone r = RingtoneManager.getRingtone(MainActivity.this, defaultSoundUri);
		r.play();
	} catch (Exception e) {
		e.printStackTrace();
	}
}

Lock Screen Notification


If you want notification to be shown even when device is locked it can be done by calling on notificationChannel reference .
 NotificationChannel channel = new NotificationChannel(channedId,
		channedId,
		NotificationManager.IMPORTANCE_HIGH);
channel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);


Sample Example



Lets see sample example where we will have two activity one is MainActivity and another NotificationActivity 

  1.  In MainActivity we will have button on click of create notification and notify .
  2. When a notification is called launch NotificationActivity and retrieve notification data .

1. XML Layout


Create XML Layout inside res/layout/

1.a  XML Layout for MainActivity  

file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/politics"
        style="@style/btn_style"
        android:text="@string/channel_politics" />

    <Button
        android:id="@+id/sports"
        style="@style/btn_style"
        android:text="@string/channel_sports" />

    <Button
        android:id="@+id/entertainment"
        style="@style/btn_style"
        android:text="@string/channel_entertainment" />

</LinearLayout>

2.b XML Layout for NotificationActivity 

file :  activity_notify.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">

    <TextView
        android:id="@+id/notifyText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="22sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>


2. Activities


2.a MainActivity

file : MainActivity.java
package com.tutorialsbuzz.notification;

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.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

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

        initViews();
    }

    private void initViews() {
        Button politics, sports, entertainment;

        politics = findViewById(R.id.politics);
        sports = findViewById(R.id.sports);
        entertainment = findViewById(R.id.entertainment);

        politics.setOnClickListener(this);
        sports.setOnClickListener(this);
        entertainment.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.politics:
                // politics politics
                createNotification(
                        getResources().getString(R.string.channel_politics),
                        getResources().getString(R.string.politics_content),
                        getResources().getString(R.string.channel_politics),
                        NotificationCompat.PRIORITY_HIGH,
                        100
                );
                break;

            case R.id.sports:
                //Sports politics
                createNotification(
                        getResources().getString(R.string.channel_sports),
                        getResources().getString(R.string.sports_content),
                        getResources().getString(R.string.channel_sports),
                        NotificationCompat.PRIORITY_DEFAULT,
                        101
                );
                break;

            case R.id.entertainment:
                //Entertainment Notification
                createNotification(
                        getResources().getString(R.string.channel_entertainment),
                        getResources().getString(R.string.entertainment_content),
                        getResources().getString(R.string.channel_entertainment),
                        NotificationCompat.PRIORITY_LOW,
                        102
                );

                break;
        }
    }

    /**
     * Create Notification
     * Param
     * 1. title
     * 2. content
     * 3. channelId
     * 4.priorty
     * 5. notificationId
     */

    private void createNotification(String title, String content,
                                    String channedId, int priorty, int notificationID) {


        Intent intent = new Intent(this, NotifyActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        Bundle extras = new Bundle();
        extras.putString(NotifyActivity.notify_title, title);
        extras.putString(NotifyActivity.notify_content, content);
        intent.putExtras(extras);
        intent.setAction(Intent.ACTION_VIEW);

        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), notificationID, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(getApplicationContext(), channedId)
                        .setSmallIcon(R.drawable.ic_notifications_active)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                        .setAutoCancel(true)
                        .setLights(Color.BLUE, 500, 500)
                        .setVibrate(new long[]{500, 500, 500})
                        .setPriority(priorty)
                        .setContentTitle(title)
                        .setContentText(content)
                        .setContentIntent(pendingIntent)
                        .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);


        // Since android Oreo notification channel is needed.
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MainActivity.this);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channedId,
                    channedId,
                    NotificationManager.IMPORTANCE_HIGH);
            channel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            notificationManager.createNotificationChannel(channel);
        }
        Notification notification = notificationBuilder.build();

        notificationManager.notify(notificationID, notification);

        playNotificationSound();
    }

    public void playNotificationSound() {
        try {
            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(MainActivity.this, defaultSoundUri);
            r.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 2.b NotifyActivity

file : NotifyActivity.java
package com.tutorialsbuzz.notification;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class NotifyActivity extends AppCompatActivity {

    public static String notify_title = "notify_title";
    public static String notify_content = "notify_content";

    private TextView textView;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notify);
        textView = findViewById(R.id.notifyText);
        updateUI();
    }

    private void updateUI() {
        String notifyData =
                getIntent().getExtras().get(notify_title) + " \n" +
                        getIntent().getExtras().get(notify_content);

        textView.setText(notifyData);
    }

}



No comments:

Post a Comment