Skip to main content

android - How to create a Notification

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#a3aee1"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Issue A Notification"
        android:layout_margin="50dp"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcode;

import android.app.NotificationManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.graphics.Bitmap;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Resources mResources;
    private RelativeLayout mRelativeLayout;
    private Button mButton;

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

        // Get the application context
        mContext = getApplicationContext();

        // Get the Resources
        mResources = getResources();

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mButton = (Button) findViewById(R.id.btn);

        // Set a click listener for Button widget
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*
                    NotificationCompat.Builder
                        Builder class for NotificationCompat objects. Allows easier control over all
                        the flags, as well as help constructing the typical notification layouts.

                        On platform versions that don't offer expanded notifications, methods that
                        depend on expanded notifications have no effect.

                        For example, action buttons won't appear on platforms prior to Android 4.1.
                        Action buttons depend on expanded notifications, which are only available
                        in Android 4.1 and later.

                        For this reason, you should always ensure that UI controls in a notification
                        are also available in an Activity in your app, and you should always start
                        that Activity when users click the notification. To do this, use the
                        setContentIntent() method.
                */

                /*
                    public NotificationCompat.Builder (Context context)
                        Constructor. Automatically sets the when field to System.currentTimeMillis()
                        and the audio stream to the STREAM_DEFAULT.

                    Parameters
                        context : A Context that will be used to construct the RemoteViews. The
                        Context will not be held past the lifetime of this Builder object.
                */

                // Initialize a new instance of NotificationCompat.Builder object
                NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

                /*
                    public NotificationCompat.Builder setSmallIcon (int icon)
                        Set the small icon to use in the notification layouts. Different classes of
                        devices may return different sizes.

                    Parameters
                        icon : A resource ID in the application's package of the drawble to use.
                */

                // Set the notification small icon
                builder.setSmallIcon(R.drawable.notification_small_icon);

                // Get a bitmap from drawable resource
                Bitmap bitmap = BitmapFactory.decodeResource(
                        mResources,
                        R.drawable.notification_large_icon
                );

                /*
                    public NotificationCompat.Builder setLargeIcon (Bitmap icon)
                        Set the large icon that is shown in the ticker and notification.
                */

                // Set a large icon for notification
                builder.setLargeIcon(bitmap);

                /*
                    setContentTitle(CharSequence title)
                        Set the title (first row) of the notification, in a standard notification.
                */

                // Set a title for notification
                builder.setContentTitle("Notification Title");

                /*
                    setContentText(CharSequence text)
                        Set the text (second row) of the notification, in a standard notification.
                */

                // Set the notification text
                builder.setContentText("Hello! Notification service.");

                // Set an id for the current notification
                int notificationId = 001;

                /*
                    NotificationManager
                        Class to notify the user of events that happen. This is how you tell the
                        user that something has happened in the background.

                         Each of the notify methods takes an int id parameter and optionally a String
                         tag parameter, which may be null. These parameters are used to form a pair
                         (tag, id), or (null, id) if tag is unspecified. This pair identifies this
                         notification from your app to the system, so that pair should be unique
                         within your app. If you call one of the notify methods with a (tag, id) pair
                         that is currently active and a new set of notification parameters, it will
                         be updated. For example, if you pass a new status bar icon, the old icon in
                         the status bar will be replaced with the new one. This is also the same tag
                         and id you pass to the cancel(int) or cancel(String, int) method to clear
                         this notification.

                         You do not instantiate this class directly; instead, retrieve it through
                         getSystemService(Class).
                */

                /*
                    public final T getSystemService (Class<T> serviceClass)
                        Return the handle to a system-level service by class.

                         Note: System services obtained via this API may be closely associated with
                         the Context in which they are obtained from. In general, do not share the
                         service objects between various different contexts (Activities,
                         Applications, Services, Providers, etc.)

                    Parameters
                        serviceClass : The class of the desired service.

                    Returns
                        The service or null if the class is not a supported system service.
                */
                // Get an instance of NotificationManager
                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

                /*
                    public void notify (int id, Notification notification)
                        Post a notification to be shown in the status bar. If a notification with
                        the same id has already been posted by your application and has not yet been
                        canceled, it will be replaced by the updated information.

                    Parameters
                        id : An identifier for this notification unique within your application.
                        notification : A Notification object describing what to show the user.
                            Must not be null.
                */

                // Finally, show the notification on notification drawer
                manager.notify(notificationId,builder.build());
           }
        });
    }
}
More android examples

Popular posts from this blog

How to use NumberPicker in Android

Table of contentsNumberPicker ExamplesetOnValueChangedListeneronValueChange()setWrapSelectorWheel()setMinValue()setMinValue()setMaxValue()NumberPicker with String ArraysetDisplayedValues()String Array1. NumberPicker Example activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity" android:background="#ffffff" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25dp" android:text="Select a number..." /> <NumberPicker android:id="@+id/np" …

TextView new line (multiline) in android

TextView new line (multiline) TextView display text on android app. by default, TextView show text on a single line, and if it is long then TextView take more lines to display its text. android developers can generate a new line on TextView both programmatically and syntactically. android developers can make a multiline TextView without splitting text to multiline by android:minLines attribute.

the following android example code demonstrate us how can we syntactically create a new line on TextView widget by xml layout file and string resource file.

the simplest way to create a new line on TextView is android:text attribute. android:text attribute allow us to display text on android app. we can add a simple '\n' to TextView text where we want to start a new line. in this way we can create a multiline TextView widget in android app. we can assign android:text attribute value by this way android:text="Line1 \n Line2 \n Line3" for a TextView widget. this value will…

How to change TextView font size in android

TextView font size TextView widget display text on android application. we can set or change TextView font size statically by declarative syntax in xml layout file or programmatically at run time in java file. even we can use an xml file source to define font size.

the following example code demonstrate us how can we define TextView font size in xml layout file and how can we uses dimens.xml to reference font size. in this example we did not changes any coding in java file, so here we only include the layout xml file and dimens.xml file. activity_main.xml <LinearLayout 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:orientation="vertical" android:layout_margin="25dp" tools:context=".MainActivity" > <TextView android:id=&…