Thursday, November 19, 2015

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