悬挂式Notification 停留几秒后自动消失 且保留状态栏的通知(自定义消息)

本文介绍如何在Android应用中实现自定义的通知样式,包括普通通知和悬挂式通知,通过代码示例展示了如何设置通知的内容、图标、行为等,并确保通知既醒目又便于用户查看。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:通知目前有三种  普通通知 折叠式通知 悬挂式通知

我现在想让app弹出悬挂式通知 ,醒目些,通知自动消失或手动划除后,下滑状态栏我还想看到通知;

只用普通的通知,只能在状态栏提示,提示不够明显;只用悬挂式的,提示够明显,但是自动消失或手动划除后,在状态就消失了,不方便再次查看;

最后我就一条自定义消息,我同时弹出一个普通通知和一个悬挂式通知,定义5秒后悬挂式通知消失,悬挂式通知消失后还可下滑查看通知。

下面是简单代码  仅供参考:

悬挂式通知是android5.0以后出来的,在5.0以下手机不支持。。。

Notification管理

NotificationManager  nm= (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)

final Notification.Builder builder = new Notification.Builder(context);
        Intent intent = new Intent(context, PublishedAboutActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        builder.setContentIntent(pendingIntent);//普通消息
        builder.setWhen(System.currentTimeMillis());
        builder.setSmallIcon(R.mipmap.ic_shop_keji);
        builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_shop_keji));
        builder.setAutoCancel(true);
        builder.setDefaults(NotificationCompat.DEFAULT_ALL);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder.setVisibility(Notification.VISIBILITY_PUBLIC);
        }
        builder.setContentTitle("自定义消息标题");
        builder.setContentText("自定义消息内容");
        nm.notify(notifyId, builder.build());//普通消息提示  显示在状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//SDK版本大于等于21才有悬挂式通知栏
            Intent xintent = new Intent(context, PublishedAboutActivity.class);
            xintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent hangIntent = PendingIntent.getActivity(context, 0, xintent,      PendingIntent.FLAG_CANCEL_CURRENT);
            builder.setFullScreenIntent(hangIntent, true);//悬挂式通知  悬挂在手机屏上方
            notifyTag = notifyId + "jpush";//由于同一条消息  id 一样  ,有针对悬挂式通知打了一个tag;
            nm.notify(notifyTag, notifyId, builder.build());
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(5000);//五秒后悬挂式通知消失
                        nm.cancel(notifyTag, notifyId);//按tag id 来清除消息
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值