安卓(Android) 怎么从PendingEntent创建通知(Notification)

2019年10月8日23:10:52安卓(Android) 怎么从PendingEntent创建通知(Notification)已关闭评论 318 1945字阅读6分29秒

1.简介

安卓(Android) 怎么从PendingEntent创建通知(Notification)?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


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 {
            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 {
            
            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) {
            
        }
        return notification;
    }
}

 
继续阅读
编程十万个怎么办