Android常用通知

1.一般的通知步骤

    1. Notification代码如下
//自定义打开的界面
        Intent intent = new Intent(this, NoticeReceiveActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //intent里面可以携带参数
        intent.putExtra("key","来自通知");
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 9
                , intent, PendingIntent.FLAG_UPDATE_CURRENT);

//1,获取NotificationManager实例
         nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //2,创建Notification实例
        Notification.Builder builder = new Notification.Builder(this);
         builder.setAutoCancel(true)  //设置点击通知后自动取消通知
                .setContentTitle("标题")  //通知标题
                .setContentText("内容简介")  //通知第二行的内容
                .setContentIntent(pendingIntent)  //点击通知后,发送指定的PendingIntent
                .setSmallIcon(R.mipmap.scbg);  //通知图标,必须设置否则通知不显示


        Notification build = builder.build();
        //3,发送通知
        nm.notify(1,build);
    1. NotificationCompat代码如下
 NotificationManager nm;
    public void testOne2(View view) {
        //自定义打开的界面
        Intent intent = new Intent(this, NoticeReceiveActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //intent里面可以携带参数
        intent.putExtra("key","来自通知");
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 9
                , intent, PendingIntent.FLAG_UPDATE_CURRENT);

        //1,获取NotificationManager实例
         nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //2,获取通知的构造器
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        Notification notification = builder
                .setContentTitle("任意标题")//设置标题
                .setContentText("设置任意内容白费劲啊飞机的飞机啊房间爱疯没法讲方法诶白费劲啊飞机的飞机啊房间爱疯没法讲方法诶白费劲啊飞机的飞机啊房间爱疯没法讲方法诶白费劲啊飞机的飞机啊房间爱疯没法讲方法诶")
                .setAutoCancel(true)//设置可取消
                .setContentInfo("设置任意附件信息")
                .setShowWhen(true)//设置是否显示时间
                .setTicker("通知来了")//设置通知首次出现提示
                .setPriority(Notification.PRIORITY_DEFAULT)//设置通知的优先级,默认为0
                .setDefaults(Notification.DEFAULT_VIBRATE)//设置振动声音等,需要振动权限
                .setContentIntent(pendingIntent)//自定义打开的界面
                .setWhen(System.currentTimeMillis())//设置时间,long类型自动转换
                .setSmallIcon(R.mipmap.scbg)//设置小图标,必须设置
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.cktl4))//设置大图标
                .build();
        //3,发送通知
        nm.notify(2,notification);
    }

2.几种常用通知工具使用

  • 1.对于8.0适配处理,需要创建通知渠道
  //提前对通知渠道处理,默认创建多种
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannels.createAllNotificationChannels(this);
        }
    1. 普通通知
public void normal(View view) {
        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.LOW);

        notifyUtils.notifyNormal(null,R.mipmap.logo,0,null,"title",
                "content",2,false,false,false);
    }
    1. 自定义布局通知
      1.这种方法有的手机会有高度限制(自定义布局高度压缩为常见通知高度,适用高度和普通通知高度相同)
 public void custom1(View view) {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notice);

        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.LOW);

        notifyUtils.notifyCustomView(remoteViews,null,
                R.mipmap.logo,0,"hello",9,false,false,false);
    }

2.正常布局

public void custom2(View view) {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notice);

        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.LOW);

        notifyUtils.notifyCustomView2(remoteViews,null,
                R.mipmap.logo,0,"hello",9,false,false,false);
    }
  • 3.带大图通知
public void bigIconListener(View view) {//大图在魅族上会重叠
        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.LOW);
        notifyUtils.notifyBigPic(null,R.mipmap.cktl4,0,
                "hello","邮件","这是一封重要的邮件",
                R.mipmap.scbg,8,false,true,true);
    }
  • 4.多行文字通知
 public void moreTextListener(View view) {
        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.IMPORTANCE);

        notifyUtils.notifyNormailMoreline(null,R.mipmap.logo,0,
                null,"多行文字",
                "这是一封重要的邮件这是一封重要的邮件这是一封重要的邮件这是一封重要的邮件这是一封重要的邮件" +
                        "这是一封重要的邮件这是一封重要的邮件这是一封重要的邮件",
                7,false,false,false);

    }
  • 5.带点击通知
public void buttonListener(View view) {
        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.IMPORTANCE);
        notifyUtils.notifyButton(R.mipmap.cktl4,0,R.mipmap.cktl4,"左侧文字",null,
                R.mipmap.logo,"右侧",null,null,"带按钮的通知",
                "通知通知套中套总投资天天",23,false,false,false);
    }
  • 6,head up
    经测试,样式和带按钮点击类似
public void headupListener(View view) {

        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.IMPORTANCE);
        notifyUtils.notifyHeadUp(null,R.mipmap.logo,R.mipmap.scbg,
                "通知","标题","简单内容",R.mipmap.ic_launcher,
                "左边",null,R.mipmap.scbg,"右边"
                ,null,22, false,false,false);

    }

3,创建通知渠道类

public class NotificationChannels {
    public final static String CRITICAL = "critical";
    public final static String IMPORTANCE = "importance";
    public final static String DEFAULT = "default";
    public final static String LOW = "low";
    public final static String MEDIA = "media";

    public static final String CHANNEL_CRITICAL = "Critical events";
    public static final String CHANNEL_IMPORTANCE = "Importance events";
    public static final String CHANNEL_DEFAULT = "Default events";
    public static final String CHANNEL_LOW = "Low events";
    public static final String CHANNEL_MEDIA = "Media events";

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void createAllNotificationChannels(Context context) {
        Log.e("MMM", "createAllNotificationChannels: " );
        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if(nm == null) {
            return;
        }

        //创建全部渠道,也可以根据需求创建
        NotificationChannel mediaChannel = new NotificationChannel(
                MEDIA,
                CHANNEL_MEDIA,
                NotificationManager.IMPORTANCE_DEFAULT);
        mediaChannel.setSound(null,null);
        mediaChannel.setVibrationPattern(null);

        nm.createNotificationChannels(Arrays.asList(
                new NotificationChannel(
                        CRITICAL,
                        CHANNEL_CRITICAL,
                        NotificationManager.IMPORTANCE_HIGH),
                new NotificationChannel(
                        IMPORTANCE,
                       CHANNEL_IMPORTANCE,
                        NotificationManager.IMPORTANCE_DEFAULT),
                new NotificationChannel(
                        DEFAULT,
                        CHANNEL_DEFAULT,
                        NotificationManager.IMPORTANCE_LOW),
                new NotificationChannel(
                        LOW,
                        CHANNEL_LOW,
                        NotificationManager.IMPORTANCE_MIN),
                //custom notification channel
                mediaChannel
        ));
    }
}

4.通知类

public class NotifyUtils {

    private Context mContext;
    private NotificationManager mNm;
    private NotificationCompat.Builder mBuilder;
    private Notification notification;

    public NotifyUtils(Context context,String channelId) {
        mContext = context;
        // 获取系统服务来初始化对象
        mNm = (NotificationManager) mContext
                .getSystemService(Activity.NOTIFICATION_SERVICE);
        //判断是否是8.0,8.0创建通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//默认聊天高级通知
            mBuilder = new NotificationCompat.Builder(mContext,channelId);
        }else {
            mBuilder = new NotificationCompat.Builder(mContext);
        }

    }


    /**
     * 设置在顶部通知栏中的各种信息
     *
     * @param pendingIntent
     * @param smallIcon
     * @param ticker
     */
    private void setCompatBuilder(PendingIntent pendingIntent, int smallIcon, int largeIcon,
                                  String ticker,
                                  String title, String content, boolean sound, boolean vibrate, boolean lights) {


        mBuilder.setContentIntent(pendingIntent);// 该通知要启动的Intent
        mBuilder.setSmallIcon(smallIcon);// 设置顶部状态栏的小图标
        mBuilder.setTicker(ticker);// 在顶部状态栏中的提示信息

        mBuilder.setContentTitle(title);// 设置通知中心的标题
        mBuilder.setContentText(content);// 设置通知中心中的内容
        mBuilder.setWhen(System.currentTimeMillis());
        if (largeIcon != 0){//默认0是没有大图
            mBuilder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), largeIcon));
        }
        /*
         * 将AutoCancel设为true后,当你点击通知栏的notification后,它会自动被取消消失,
         * 不设置的话点击消息后也不清除,但可以滑动删除
         */
        mBuilder.setAutoCancel(true);
        // 将Ongoing设为true 那么notification将不能滑动删除
        // notifyBuilder.setOngoing(true);
        /*
         * 从Android4.1开始,可以通过以下方法,设置notification的优先级,
         * 优先级越高的,通知排的越靠前,优先级低的,不会在手机最顶部的状态栏显示图标
         */
        mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
        /*
         * Notification.DEFAULT_ALL:铃声、闪光、震动均系统默认。
         * Notification.DEFAULT_SOUND:系统默认铃声。
         * Notification.DEFAULT_VIBRATE:系统默认震动。
         * Notification.DEFAULT_LIGHTS:系统默认闪光。
         * notifyBuilder.setDefaults(Notification.DEFAULT_ALL);
         */
        int defaults = 0;

        if (sound) {
            defaults |= Notification.DEFAULT_SOUND;
        }
        if (vibrate) {
            defaults |= Notification.DEFAULT_VIBRATE;
        }
        if (lights) {
            defaults |= Notification.DEFAULT_LIGHTS;
        }

        mBuilder.setDefaults(defaults);
    }

    /**普通的通知
     * @param pendingIntent
     * @param smallIcon
     * @param ticker
     * @param title
     * @param content
     * @param id
     * @param sound
     * @param vibrate
     * @param lights
     */
    public void notifyNormal(PendingIntent pendingIntent, int smallIcon,int largeIcon,
                                       String ticker, String title, String content, int id,
                                       boolean sound, boolean vibrate, boolean lights) {
        setCompatBuilder(pendingIntent, smallIcon, largeIcon, ticker, title, content, sound, vibrate, lights);
        sent(id);
    }

    /**
     * 自定义视图的通知(默认64dp)
     *
     * @param remoteViews
     * @param pendingIntent
     * @param smallIcon
     * @param ticker
     */
    public void notifyCustomView(RemoteViews remoteViews, PendingIntent pendingIntent,
                                  int smallIcon, int largeIcon, String ticker, int id,
                                  boolean sound, boolean vibrate, boolean lights) {

        setCompatBuilder(pendingIntent, smallIcon, largeIcon, ticker, null, null, sound, vibrate, lights);

        notification = mBuilder.build();
        notification.contentView = remoteViews;
        // 发送该通知
        mNm.notify(id, notification);
    }

    /**自定义视图的通知
     * @param remoteViews
     * @param pendingIntent
     * @param smallIcon
     * @param ticker
     * @param id
     * @param sound
     * @param vibrate
     * @param lights
     */
    public void notifyCustomView2(RemoteViews remoteViews, PendingIntent pendingIntent,
                                 int smallIcon, int largeIcon, String ticker, int id,
                                 boolean sound, boolean vibrate, boolean lights){

        setCompatBuilder(pendingIntent, smallIcon, largeIcon, ticker, null, null, sound, vibrate, lights);

        Notification notification = mBuilder.build();
        notification.bigContentView=remoteViews;
        mNm.notify(id, notification);
    }

    /**
     * 容纳大图片的通知
     *
     * @param pendingIntent
     * @param smallIcon
     * @param ticker
     * @param title
     * @param bigPic
     */
    public void notifyBigPic(PendingIntent pendingIntent, int smallIcon, int largeIcon, String ticker,
                              String title, String content, int bigPic, int id,boolean sound, boolean vibrate, boolean lights) {

        setCompatBuilder(pendingIntent, smallIcon, largeIcon, ticker, title, null, sound, vibrate, lights);
        NotificationCompat.BigPictureStyle picStyle = new NotificationCompat.BigPictureStyle();
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = true;
        options.inSampleSize = 2;
        Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(),
                bigPic, options);
        picStyle.bigPicture(bitmap);
        picStyle.bigLargeIcon(bitmap);
        mBuilder.setContentText(content);
        mBuilder.setStyle(picStyle);
        sent(id);
    }

    /**
     * 可以容纳多行提示文本的通知信息 (因为在高版本的系统中才支持,所以要进行判断)
     *
     * @param pendingIntent
     * @param smallIcon
     * @param ticker
     * @param title
     * @param content
     */
    public void notifyNormailMoreline(PendingIntent pendingIntent, int smallIcon, int largeIcon,
                                      String ticker,
                                        String title, String content, int id, boolean sound, boolean vibrate, boolean lights) {

        final int sdk = Build.VERSION.SDK_INT;
        if (sdk < Build.VERSION_CODES.JELLY_BEAN) {
            notifyNormal(pendingIntent, smallIcon, largeIcon,ticker, title, content, id, sound, vibrate, lights);
        } else {
            setCompatBuilder(pendingIntent, smallIcon, largeIcon,ticker, title,content,true, true, false);

            NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle()
                    .bigText(content);
            mBuilder.setStyle(bigTextStyle);
            sent(id);
        }
    }

    /**
     * 里面有两个按钮的通知
     *
     * @param smallIcon
     * @param leftbtnicon
     * @param lefttext
     * @param leftPendIntent
     * @param rightbtnicon
     * @param righttext
     * @param rightPendIntent
     * @param ticker
     * @param title
     * @param content
     */
    public void notifyButton(int smallIcon, int largeIcon, int leftbtnicon, String lefttext, PendingIntent leftPendIntent,
                             int rightbtnicon, String righttext, PendingIntent rightPendIntent, String ticker,
                              String title, String content, int id, boolean sound, boolean vibrate, boolean lights) {


        setCompatBuilder(rightPendIntent, smallIcon, largeIcon, ticker, title, content, sound, vibrate, lights);
        mBuilder.addAction(leftbtnicon,
                lefttext, leftPendIntent);
        mBuilder.addAction(rightbtnicon,
                righttext, rightPendIntent);
        sent(id);
    }

    public void notifyHeadUp(PendingIntent pendingIntent, int smallIcon, int largeIcon,
                              String ticker, String title, String content, int leftbtnicon, String lefttext,
                              PendingIntent leftPendingIntent, int rightbtnicon, String righttext,
                              PendingIntent rightPendingIntent, int id,
                              boolean sound, boolean vibrate, boolean lights) {

        setCompatBuilder(pendingIntent, smallIcon, largeIcon,ticker, title, content, sound, vibrate, lights);
        //mBuilder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), largeIcon));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mBuilder.addAction(leftbtnicon,
                    lefttext, leftPendingIntent);
            mBuilder.addAction(rightbtnicon,
                    righttext, rightPendingIntent);
        } else {
            Toast.makeText(mContext, "版本低于Andriod5.0,无法体验HeadUp样式通知", Toast.LENGTH_SHORT).show();
        }
        sent(id);
    }

    /**
     * 发送通知
     */
    private void sent(int id) {
        notification = mBuilder.build();
        // 发送该通知
        mNm.notify(id, notification);
    }

    public void clear() {
        // 取消通知
        mNm.cancelAll();
    }
    public void removeId(int id){
        //id不存在会崩溃
        mNm.cancel(id);
    }
}

5.参考文献

上面都是常用简单通知,其他类型的通知,及适配问题可以参考其他文献.
Android--通知之Notification
Android通知栏介绍与适配总结
是时候来了解android7了:通知直接回复
Android7.0 通知直接回复
Android通知栏微技巧,8.0系统中通知栏的适配
Android 8.0中各种通知写法汇总

6,源码

demo

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,340评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,762评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,329评论 0 329
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,678评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,583评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,995评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,493评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,145评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,293评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,250评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,267评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,973评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,556评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,648评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,873评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,257评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,809评论 2 339

推荐阅读更多精彩内容

  • 我 要一道长疤 要眉骨高高 要手指温热 要接一杯清水 要给你盖床薄被 我要 你频频想到我 食不下咽 寝难安 我要回...
    归一白阅读 89评论 0 0
  • 前段时间,关于家长陪孩子写作业的相关段子在朋友圈里、微博上引发了大量转载,这些段子红火的原因,想必是让家长们产生了...
    麦子轻扬阅读 830评论 1 4
  • 离群索居者不是野兽,便是神灵。——亚里士多德 初中时,《守望的距离》这本书是老师规定的必读书目,第一次品读就爱不释...
    费汐宁阅读 396评论 4 5
  • inbody是给刚来健身的朋友们作为身体的参考,因为你们是白纸,会对你们有作用,那些数据。而对我常年健身的人...
    你喂喂阅读 232评论 0 0