Android - app内部通知通知栏通知Notification (Kotlin)

一、简述

先把通知权限打开

为什么写,因为在学kotlin刚好顺手写一下,整块代码在最后

图示效果:(图片来源于网络)

1、首先需要一个NotificationManager对通知进行管理,可以通过调用Context的 getSystemService()方法获取。getSystemService()方法接收一个字符串参数用于确定 获取系统的哪个服务,这里我们传入Context.NOTIFICATION_SERVICE即可。因此,获取 NotificationManager的实例就可以写成:

val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

接下来要使用NotificationChannel类构建一个通知渠道,并调用NotificationManager的 createNotificationChannel()方法完成创建。由于NotificationChannel类和 createNotificationChannel()方法都是Android 8.0系统中新增的API,因此我们在使用 的时候还需要进行版本判断才可以,写法如下:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
 val channel = NotificationChannel(channelId, channelName, importance)
 manager.createNotificationChannel(channel)
}

创建一个通知渠道至少需要渠道ID、渠道名称以及重要等级这3个参数,其中渠道ID可以随便定 义,只要保证全局唯一性就可以。渠道名称是给用户看的,需要可以清楚地表达这个渠道的用 途。通知的重要等级主要有IMPORTANCE_HIGH、IMPORTANCE_DEFAULT、 IMPORTANCE_LOW、IMPORTANCE_MIN这几种,对应的重要程度依次从高到低。不同的重要等 级会决定通知的不同行为,后面我们会通过具体的例子进行演示。当然这里只是初始状态下的 重要等级,用户可以随时手动更改某个通知渠道的重要等级,开发者是无法干预的。

2、了解了如何创建通知渠道之后,看一下通知的使用。既可以在Activity里创建,也可以在BroadcastReceiver里创建,当然还可以在后面 我们即将学习的Service里创建。相比于BroadcastReceiver和Service,在Activity里创建通 知的场景还是比较少的,因为一般只有当程序进入后台的时候才需要使用通知。 不过,无论是在哪里创建通知,整体的步骤都是相同的。

/**首先需要使用一个Builder构造器来创建Notification对象,但问题在于,
Android系统的每 一个版本都会对通知功能进行或多或少的修改,API不稳定
的问题在通知上凸显得尤其严重,比 方说刚刚介绍的通知渠道功能在Android
 8.0系统之前就是没有的。那么该如何解决这个问题 呢?其实解决方案我们之
前已经见过好几回了,就是使用AndroidX库中提供的兼容API。 AndroidX库中
提供了一个NotificationCompat类,使用这个类的构造器创建 Notification
对象,就可以保证我们的程序在所有Android系统版本上都能正常工作了:*/
val notification = NotificationCompat.Builder(context, channelId).build()

二、实际使用

演示图片在文章首页

//通知
        //1.普通通知
        //解决通知消失的方法有两种:一种是在
        //NotificationCompat.Builder中再连缀一个setAutoCancel()方法,一种是显式地调用
        //NotificationManager的cancel()方法将它取消
        
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel("normal", "Normal", NotificationManager.IMPORTANCE_DEFAULT)
            manager.createNotificationChannel(channel)
        }

        findViewById<View>(R.id.bt4).setOnClickListener {
            var intent = Intent(this,notificationActivity::class.java)
            val padinintent = PendingIntent.getActivity(this,0,intent,0)
            val notification = NotificationCompat.Builder(this, "normal")
                .setContentTitle("标题")
                .setContentText("内容")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setLargeIcon(
                    BitmapFactory.decodeResource(resources, android.R.drawable.btn_star_big_on)
                )
                .setContentIntent(padinintent)
                .setAutoCancel(true)
                .build()
            manager.notify(1, notification)
        }

        //长字符通知
        findViewById<View>(R.id.bt5).setOnClickListener {
            var intent = Intent(this,notificationActivity::class.java)
            val padinintent = PendingIntent.getActivity(this,0,intent,0)
            val notification = NotificationCompat.Builder(this, "normal")
                .setContentTitle("标题")
                .setStyle(NotificationCompat.BigTextStyle()
                    .bigText("Learn how to build\n" +
                        " notifications, send and sync data, and use voice actions. Get the official\n" +
                        " Android IDE and developer tools to build apps for Android."))
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setLargeIcon(
                    BitmapFactory.decodeResource(resources, android.R.drawable.btn_star_big_on)
                )
                .setContentIntent(padinintent)
                .setAutoCancel(true)
                .build()
            manager.notify(1, notification)
        }

        //大图通知
        findViewById<View>(R.id.bt6).setOnClickListener {
            var intent = Intent(this,notificationActivity::class.java)
            val padinintent = PendingIntent.getActivity(this,0,intent,0)
            val notification = NotificationCompat.Builder(this, "normal")
                .setContentTitle("标题")
                .setStyle(NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory
                    .decodeResource(resources, android.R.drawable.presence_online)))
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setLargeIcon(
                    BitmapFactory.decodeResource(resources, android.R.drawable.btn_star_big_on)
                )
                .setContentIntent(padinintent)
                .setAutoCancel(true)
                .build()
            manager.notify(1, notification)
        }

        //app内部通知
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel2 = NotificationChannel("important", "Important",
                NotificationManager.IMPORTANCE_HIGH)
            manager.createNotificationChannel(channel2)
        }
        findViewById<View>(R.id.bt7).setOnClickListener {
            val intent = Intent(this, notificationActivity::class.java)
            val pi = PendingIntent.getActivity(this, 0, intent, 0)
            val notification = NotificationCompat.Builder(this, "important")
                .setContentTitle("标题")
                .setContentText("内容")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setLargeIcon(
                    BitmapFactory.decodeResource(resources, android.R.drawable.btn_star_big_on)
                )
                .setContentIntent(pi)
                .setAutoCancel(true)
                .build()
            manager.notify(1, notification)
        }

被跳转的activity

class notificationActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_notification)

        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as
                NotificationManager
        manager.cancel(1)

    }
}

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".activity.MainActivity">

    <Button
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="toase"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/bt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="调用viewmodel方法"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/bt3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳转"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/bt4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="普通通知"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/bt5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="长字符通知"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/bt6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="大图通知"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/bt7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="app内部通知"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</LinearLayout>

到这里就结束了

下边是一些解释

1.PendingIntent

从名字上看起来就和Intent有些类似,它们确实存在不少共同点。比如它们都可 以指明某一个“意图”,都可以用于启动Activity、启动Service以及发送广播等。不同的是, Intent倾向于立即执行某个动作,而PendingIntent倾向于在某个合适的时机执行某个动作。所 以,也可以把PendingIntent简单地理解为延迟执行的Intent。 PendingIntent的用法同样很简单,它主要提供了几个静态方法用于获取PendingIntent的实 例,可以根据需求来选择是使用getActivity()方法、getBroadcast()方法,还是 getService()方法。这几个方法所接收的参数都是相同的:第一个参数依旧是Context,不 用多做解释;第二个参数一般用不到,传入0即可;第三个参数是一个Intent对象,我们可以通 www.blogss.cn 过这个对象构建出PendingIntent的“意图”;第四个参数用于确定PendingIntent的行为,有 FLAG_ONE_SHOT、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT和 FLAG_UPDATE_CURRENT这4种值可选,每种值的具体含义你可以查看文档,通常情况下这个 参数传入0就可以了。 对PendingIntent有了一定的了解后,我们再回过头来看一下 NotificationCompat.Builder。这个构造器还可以连缀一个setContentIntent()方 法,接收的参数正是一个PendingIntent对象。因此,这里就可以通过PendingIntent构建一个 延迟执行的“意图”,当用户点击这条通知时就会执行相应的逻辑。 现在我们来优化一下NotificationTest项目,给刚才的通知加上点击功能,让用户点击它的时候 可以启动另一个Activity

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Android通知是一种用于显示应用程序通知的用户界面元素。它可以在屏幕的顶部或底部显示,并且可以包含文本、图像、声音和其他交互元素。通知可以帮助用户及时了解应用程序的状态和事件,例如新消息、更新、提醒和警告等。开发人员可以使用Android SDK提供的通知API来创建和管理通知,以便更好地与用户进行交互。 ### 回答2: Android 通知是一种提供给用户显示有关当前状态和行动的信息的方式,以便用户可以及时地采取必要的行动。通知可以显示来自应用程序和系统通知消息,例如电子邮件、信息和其他事件,可以让用户在不离开当前应用的情况下对这些消息进行响应。 在通知中,每个通知都包含一个图标、标题、简短的消息文本和通知时间。用户可以从通知中直接打开应用程序或查看通知的详细信息。通知还可以显示多个通知,按照时间顺序进行排序。 开发人员可以使用 Android SDK 提供的 Notification 类来创建自定义通知。可以设置通知的图标、文本、声音、震动和延迟时间等属性。还可以指定通知的优先级,以便系统在有限的屏幕空间中为用户先显示最重要的通知通知还可以与 PendingIntent 实例相关联,以便在用户单击通知时执行特定的操作,例如打开应用程序,启动活动或显示通知详细信息的专用活动。 总之,Android 通知是一种非常有用的功能,可以让用户及时了解应用程序和系统中的重要事件,并采取及时的行动。开发人员可以使用通知来实现更好的用户体验。 ### 回答3: Android 通知是一种非常有用的功能,它可以让你的应用程序以一种全新的方式与用户进行交互。在 Android 应用程序中,通知是一种特殊的 UI 元素,它显示在屏幕的顶部,并显示当前状态、事件或提示。通知通常包含一组小图标,可以展开或折叠以显示更多详细信息。 Android 通知有许多不同的用途,例如提醒用户新的消息、电子邮件、电话、提醒等等。发送通知的应用程序无需与用户保持连接,这使得通知非常适合后台服务或其他形式的低功耗通信。通知还允许用户直接从通知菜单中操作应用程序。例如,当用户收到新的电子邮件时,他们可以在通知中选择该电子邮件并立即查看其内容,而无需打开电子邮件应用程序。 Android 通知的另一个优点是它的可定制性。可以轻松地修改通知的外观、行为和内容,以满足不同应用程序的需求和设计要求。您可以为通知添加各种元素,如纯文本、小图标、大图标、进度指示器、按钮等等。这样,您可以轻松地创造与您的品牌和应用程序设计语言保持一致的通知。 在实现通知之前,您需要确保该应用程序已获得了通知权限。如果您的应用程序需要通知用户任何内容,则必须获得 Android 手机上的通知权限。可以在应用程序设置中找到此选项。 虽然 Android 通知很有用,但在某些情况下,它们可能会变得令人分心。因此,应该仔细考虑应用程序通知的数量和类型,以确保用户不会感到困扰。通知还可以消耗设备电池,因此也应考虑优化应用程序以最小化资源消耗。 Android 通知作为 Android 应用程序非常重要的一部分,可以帮助您在应用程序和用户之间建立更紧密的联系,并提供有关应用程序状态、事件和提示的有用信息。通过努力优化您的应用程序通知,您可以确保用户感到受到了关注,并且同时不会让他们感到困扰。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值