create Notification from PendingIntent - Android Android OS

Android examples for Android OS:Notification Create

Description

create Notification from PendingIntent

Demo Code


//package com.java2s;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Build;
import java.lang.reflect.Method;

public class Main {
    public static Notification createNotification(Context context,
            PendingIntent pendingIntent, String title, String text,
            int iconId) {
        Notification notification;
        if (isNotificationBuilderSupported()) {
            notification = buildNotificationWithBuilder(context,
                    pendingIntent, title, text, iconId);
        } else {/*from w  w w .j a va 2s  .c om*/
            notification = buildNotificationPreHoneycomb(context,
                    pendingIntent, title, text, iconId);
        }
        return notification;
    }

    public static boolean isNotificationBuilderSupported() {
        try {
            return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                    && Class.forName("android.app.Notification.Builder") != null;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @SuppressWarnings("deprecation")
    private static Notification buildNotificationWithBuilder(
            Context context, PendingIntent pendingIntent, String title,
            String text, int iconId) {
        android.app.Notification.Builder builder = new android.app.Notification.Builder(
                context).setContentTitle(title).setContentText(text)
                .setContentIntent(pendingIntent).setSmallIcon(iconId)
                .setAutoCancel(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            return builder.build();
        } else {
            return builder.getNotification();
        }
    }

    @SuppressWarnings("deprecation")
    private static Notification buildNotificationPreHoneycomb(
            Context context, PendingIntent pendingIntent, String title,
            String text, int iconId) {
        Notification notification = new Notification(iconId, "",
                System.currentTimeMillis());
        try {
            // try to call "setLatestEventInfo" if available
            Method m = notification.getClass().getMethod(
                    "setLatestEventInfo", Context.class,
                    CharSequence.class, CharSequence.class,
                    PendingIntent.class);
            m.invoke(notification, context, title, text, pendingIntent);
            notification.flags &= Notification.FLAG_AUTO_CANCEL;
        } catch (Exception e) {
            // do nothing
        }
        return notification;
    }
}

Related Tutorials