TrinityTuts

Create notification using Notification builder android

Last updated on March 13th, 2020 at 12:17 pm

Android notification is one of the best way to display alert message to user. In this post i explain you how to create notification using NotificationCompat.Builder in android.

NotificationManager

Android Notifications are created by the Notification class.  To use Notification class you first need to declare NotificationManager to be able to get the proper Context from the activity or service depending on your application need.

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

Android Builder classes

Notification.Builder – This class was added in Android 3.0 Honeycomb [API 11].  So if you need to support older SDK’s you will need to use NotificationCompact instead.

NotificationCompat.Builder – This class is in the version 4 Support Library (compatible Android 1.6 and up).

NotificationCompat.Builder

The NotificationCompact.Builder, similar to other class builders, provides an interface that is used to create a Notification object. NotificationCompact.Builder help you constructing the typical notification layouts. On platform versions that don’t offer expanded notifications, methods that depend on expanded notifications have no effect.

NotificationCompat.Builder Properties

.setSmallIcon() – Set Small Icon

.setContentTitle() – Set Content title

.setContentText() – Set Message

.setSound(Settings.System.DEFAULT_NOTIFICATION_URI) – Set Sound when Notification make

NotificationCompat.Builder Actions

.setContentIntent() – Set PendingIntent

PendingIntent

PendingIntent is a token that you give to a foreign application (e.g. NotificationManagerAlarmManager, Home Screen AppWidgetManager, or other 3rd party applications), which allows the foreign application to use your application’s permissions to execute a predefined piece of code. [Stackoverflow].

In simple words: PendingIntent is a way to run your intent from the notification bar/application.

Intent intent = new Intent(getApplicationContext(), NotificationDetailsActivity.class);
        intent.putExtra("msg", "hello");

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

CODE

Start your New Android Project

1. Create a new project in Android Studio from File ⇒ New ⇒ Android Application Project .

Note. You need to import google support library in your project. If you are using Android Studio you need to add support in your build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.notificationtut"
        minSdkVersion 14
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile "com.android.support:support-v4:20.0.+"
}

2. Create button in your main activity file {eg. myactivity.xml} to fire notification.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MyActivity">

    <Button
        android:id="@+id/ntf"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="load notification"/>

</RelativeLayout>

3. Now open your main java file {eg. MyActivity.java} and write this code

package com.notificationtut;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MyActivity extends Activity {
    Context context = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        Button bt = (Button) findViewById(R.id.ntf);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notification();
            }
        });
    }

    private void notification() {
        Intent intent = new Intent(getApplicationContext(), NotificationDetailsActivity.class);
        intent.putExtra("msg", "hello");

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        NotificationManager mNotificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Trinity Tuts")
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                .setStyle(new NotificationCompat.BigTextStyle().bigText("Welcome"))
                .setAutoCancel(true)
                .setContentText("Message body")
                .setContentIntent(pendingIntent);

        mNotificationManager.notify(0, mBuilder.build());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

4. Now create new file under package { eg. NotificationDetailsActivity.java }. In this file we can get data from the notification when user click on notification bar.

package com.notificationtut;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

/**
 * Created by aneh on 10/8/2014.
 */
public class NotificationDetailsActivity extends MyActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.noti);
        Intent get = getIntent();
        String data = get.getStringExtra("msg");
        Toast.makeText(getBaseContext(), "Message: "+ data, Toast.LENGTH_LONG).show();
    }
}

and also create activity inside res ⇒ layout folder to display result

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

</LinearLayout>

5. Now open your AndroidManifest.xml in which you need to enter your activity name

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MyActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>