安卓(Android) 怎么创建私有通知(Notification)

2019年10月9日22:54:01安卓(Android) 怎么创建私有通知(Notification)已关闭评论 303 1839字阅读6分7秒

1.简介

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

2.示例代码

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

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.app.TaskStackBuilder;
import java.util.List;

public class Main{
    public static void createPrivateNotification(Context context,
            Intent intent, String contentTitle, String contentText, int id) {
        PendingIntent p = getPendingIntent(context, intent, id);

        NotificationCompat.Builder b = new NotificationCompat.Builder(
                context);
        b.setDefaults(Notification.DEFAULT_ALL); 
        b.setSmallIcon(R.drawable.ic_notification_icon);
        b.setContentTitle(contentTitle); 
        b.setContentText(contentText); 
        b.setContentIntent(p); 
        b.setAutoCancel(true); 

        
        b.setVisibility(NotificationCompat.VISIBILITY_SECRET);

        NotificationManagerCompat nm = NotificationManagerCompat
                .from(context);
        nm.notify(id, b.build());
    }
    private static PendingIntent getPendingIntent(Context context,
            Intent intent, int id) {
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(intent.getComponent());
        stackBuilder.addNextIntent(intent);
        PendingIntent p = stackBuilder.getPendingIntent(id,
                PendingIntent.FLAG_UPDATE_CURRENT);
        return p;
    }
    public static void create(Context context, Intent intent,
            String contentTitle, String contentText, int id) {
        PendingIntent p = getPendingIntent(context, intent, id);

        NotificationCompat.Builder b = new NotificationCompat.Builder(
                context);
        b.setDefaults(Notification.DEFAULT_ALL); 
        b.setSmallIcon(R.drawable.ic_notification_icon); 
        b.setContentTitle(contentTitle);
        b.setContentText(contentText); 
        b.setContentIntent(p); 
        b.setAutoCancel(true); 

        b.setColor(Color.GREEN);

        NotificationManagerCompat nm = NotificationManagerCompat
                .from(context);
        nm.notify(id, b.build());
    }
}

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