Android 通知栏的使用 Android 通知栏如何使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android 通知栏的使用 Android 通知栏如何使用

一条鱼和一片海   2021-05-24 我要评论
想了解Android 通知栏怎样使用的相关内容吗,一条鱼和一片海在本文为您仔细讲解Android 通知栏的使用的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,通知栏,通知栏的使用,下面大家一起来学习吧。

一、设置通知内容

	//CHANNEL_ID,渠道ID,Android 8.0及更高版本必须要设置
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
    		//设置小图标
            .setSmallIcon(R.drawable.notification_icon)
            //设置标题
            .setContentTitle(textTitle)
            //设置内容
            .setContentText(textContent)
            //设置等级
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);

二、创建渠道

在 Android 8.0 及更高版本上提供通知,需要在系统中注册应用的通知渠道。

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.channel_name);
            String description = getString(R.string.channel_description);
            //不同的重要程度会影响通知显示的方式
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);

            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

上述代码应该在应用启动时立即执行,可以放在 Application 中进行初始化。

三、设置通知栏的点击操作

一般点击通知栏会打开对应的 Activity 界面,具体代码如下:

	//点击时想要打开的界面
    Intent intent = new Intent(this, AlertDetails.class);
    //一般点击通知都是打开独立的界面,为了避免添加到现有的activity栈中,可以设置下面的启动方式
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    //创建activity类型的pendingIntent,还可以创建广播等其他组件
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle("My notification")
            .setContentText("Hello World!")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            //设置pendingIntent
            .setContentIntent(pendingIntent)
            //设置点击后是否自动消失
            .setAutoCancel(true);    

四、显示通知

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    //notificationId 相当于通知的唯一标识,用于更新或者移除通知
    notificationManager.notify(notificationId, builder.build());

还有很多特殊功能,可以直接查看官网教程进行设置。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们