Android Notification的基本使用

本文详细介绍Android中Notification的使用方法,包括创建NotificationChannel、设置NotificationCompat.Builder等关键步骤,并提供了具体的代码实现。

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

Android Notification的基本使用

这篇很详细:https://blog.youkuaiyun.com/dsc114/article/details/51721472

 

以下是自己亲测可用的情况:支持8.0 Notification Channel

Notification的使用大体步骤:

1、 获取状态通知栏管理 
2、 实例化通知栏构造器 
3、 设置NotificationCompat.Builder 
4、 设置PendingIntent 
5、 显示

 

private void showNotification(Context context){
    final String CHANNEL_ID = "channel_id_1";
    final String CHANNEL_NAME = "channel_name_1";
//获取状态通知栏管理
    NotificationManager mNotificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
//8/0处理
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        //只在Android O之上需要渠道
        
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,
                CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);

 

//相关api设置,基本用不到

notificationChannel.canBypassDnd();//可否绕过请勿打扰模式

notificationChannel.enableLights(true);//闪光

notificationChannel.setLockscreenVisibility(VISIVILITY_SECRET);//锁屏显示通知

notificationChannel.setLightColor(Color.RED)://闪光颜色

notificationChannel.canShowBadge();//桌面laucher消息角标

notificationChannel.getAudioAttributes();//获取系统通知响铃声音的配置

notificationChannel.getGroup();//获取通知渠道组

notificationChannel.settBypassDnd(true);//设置可以绕过,请勿打扰模式

 notificationChannel.setVibrationPattern(new long[]{100,100,200});//震动的模式

notificationChannel.shouldShowLights();//是否会闪灯光


        //如果这里用IMPORTANCE_NOENE就需要在系统的设置里面开启渠道,
        //通知才能正常弹出
        
mNotificationManager.createNotificationChannel(notificationChannel);
    }

//实例化通知栏构造器
    NotificationCompat.Builder builder= new NotificationCompat.Builder(context,CHANNEL_ID);

 

//设置PendingIntent 
    Intent intent = new Intent(context, Main2Activity.class);  //需要跳转指定的页面
    
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("通知标题")
            .setContentText("通知内容")
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);
//显示
    mNotificationManager.notify(0, builder.build());
}

源码地址:https://download.youkuaiyun.com/download/silence_sep/10435392

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值