Android - Notification notification bar inside app Notification (Kotlin)

1. Brief introduction

Turn on the notification permission first

Why write it, because I just wrote it by hand when I was learning kotlin, and the whole code is at the end

Graphical effect: (picture comes from the Internet)

1. First, a NotificationManager is required to manage the notifications, which can be obtained by calling the getSystemService() method of Context. The getSystemService() method receives a string parameter to determine which service of the system to obtain, here we just pass in Context.NOTIFICATION_SERVICE. Therefore, obtaining an instance of NotificationManager can be written as:

val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

Next, use the NotificationChannel class to build a notification channel, and call the createNotificationChannel() method of NotificationManager to complete the creation. Since the NotificationChannel class and the createNotificationChannel() method are new APIs in the Android 8.0 system, we need to make version judgments when using them. The writing method is as follows:

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

Creating a notification channel requires at least three parameters: channel ID, channel name, and importance level. The channel ID can be defined at will, as long as the global uniqueness is guaranteed. The channel name is for users to see, and it needs to be able to clearly express the purpose of this channel. The importance levels of notifications mainly include IMPORTANCE_HIGH, IMPORTANCE_DEFAULT, IMPORTANCE_LOW, and IMPORTANCE_MIN, and the corresponding importance levels are from high to low. Different importance levels will determine different behaviors of notifications, which we will demonstrate through specific examples later. Of course, this is only the importance level in the initial state. Users can manually change the importance level of a notification channel at any time, and developers cannot intervene.

2. After understanding how to create a notification channel, let's take a look at the use of notifications. It can be created in the Activity or in the BroadcastReceiver, and of course it can also be created in the Service that we will learn later. Compared with BroadcastReceiver and Service, there are still relatively few scenarios for creating notifications in Activity, because notifications are generally only needed when the program enters the background. However, the overall steps are the same no matter where the notification is created.

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

2. Actual use

Demo image on the home page of the article

//通知
        //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)
        }

Jumped 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>

it's over here

Below are some explanations

1.PendingIntent

It looks similar to Intent from the name, and they do have a lot in common. For example, they can all indicate a certain "intent", and can be used to start an Activity, start a Service, and send a broadcast. The difference is that Intent tends to execute an action immediately, while PendingIntent tends to execute an action at an appropriate time. Therefore, PendingIntent can also be simply understood as an Intent that delays execution. The usage of PendingIntent is also very simple. It mainly provides several static methods for obtaining instances of PendingIntent. You can choose to use the getActivity() method, getBroadcast() method, or getService() method according to your needs. The parameters received by these methods are the same: the first parameter is still Context, no need to explain; the second parameter is generally not used, just pass in 0; the third parameter is an Intent object, We can use www.blogss.cn to construct the "intent" of PendingIntent through this object; the fourth parameter is used to determine the behavior of PendingIntent, there are 4 values: FLAG_ONE_SHOT, FLAG_NO_CREATE, FLAG_CANCEL_CURRENT and FLAG_UPDATE_CURRENT, the specific value of each value Meaning, you can check the documentation. Usually, this parameter can be passed to 0. After having a certain understanding of PendingIntent, let's look back at NotificationCompat.Builder. This constructor can also be attached with a setContentIntent() method, and the received parameter is exactly a PendingIntent object. Therefore, a delayed execution "intent" can be constructed here through PendingIntent, and the corresponding logic will be executed when the user clicks on this notification. Now let's optimize the NotificationTest project, add a click function to the notification just now, so that when the user clicks it, another Activity can be started

Guess you like

Origin blog.csdn.net/m0_59482482/article/details/129677656