如何使用Firebase云信息实现一个推送通知

147 阅读4分钟

开始使用安卓通知

通知是显示在应用程序用户界面之外的消息小部件。当通知发出时,它以图标形式出现在通知区。要查看通知的细节,用户要打开通知抽屉。

安卓通知

前提条件

要学习本教程,请确保你有以下条件。

  1. 在你的电脑上安装了[Android Studio]。
  2. 对[Kotlin]编程语言有一定了解。
  3. 对[Android]应用开发有一定了解。

应用程序设置

启动Android studio,用一个空的活动模板创建一个新的Android项目。

Android studio new project

创建和发送通知

基本通知

  • 创建一个名字为basicNotification 的函数。
  • 上面创建的函数应该有下面的代码片断。该函数创建一个带有图标、标题和通知内容的基本通知。
    private fun basicNotification() {
        val builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Test notification")
            .setContentText("Test Notification body")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        with(NotificationManagerCompat.from(this)) {
            notify(notificationId, builder.build())
        }
    }

从上面的代码片断来看。

  • NotificationCompat.Builder(this, CHANNEL_ID) 输入上下文和频道ID。在Android 8.0及以后的版本中,通知工作需要渠道ID,渠道ID用于管理以后的Android版本中的通知。
  • setSmallIcon(R.drawable.notification_icon) 设置出现在通知抽屉里的通知图标。
  • setContentTitle(textTitle) 设置显示在通知抽屉中的通知的标题。
  • setContentText(textContent) 设置通知的主体。
  • setPriority(NotificationCompat.PRIORITY_DEFAULT) 设置安卓系统将如何根据设置的优先级通知用户,它在安卓7.0及以下版本中工作。
  • 下面的代码片段创建并在系统通知抽屉中显示通知。
  with(NotificationManagerCompat.from(this)) {
            notify(notificationId, builder.build())
        }

待定的意图通知

可以在通知中添加一个意图,这样只要用户点击通知,它就会打开一个活动或来自于一个待定意图的片段。要创建一个具有待定意图的通知,在MainActivity.kt ,创建一个名称为pendingNotification 的函数,并添加下面的代码片段。

    private fun pendingNotification() {
        val intent = Intent(this, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)

        val builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("My notification")
            .setContentText("Hello World!")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
        with(NotificationManagerCompat.from(this)) {
            notify(notificationId, builder.build())
        }
    }
  • 下面的次要代码段创建了一个挂起的意图,只要通知被点击就会被执行。
val intent = Intent(this, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
  • .setContentIntent(pendingIntent) 将创建的挂起意图附加到通知上,这使得通知可以处理挂起意图的操作。

带有行动按钮的通知

安卓系统使得通过通知动作按钮来执行某些操作成为可能,例如通过通知按钮来接收来电、催眠闹钟。

通知动作是在安卓5.0版本中引入的,这就是为什么我们要用@RequiresApi(Build.VERSION_CODES.O) 注解来注释函数actionNotification

创建一个名称为actionNotification 的函数,并添加下面的代码片段。

    @RequiresApi(Build.VERSION_CODES.O)
    private fun actionsNotification() {
        val snoozeIntent = Intent(this, MyBroadCastReceiver::class.java).apply {
            action = "snooze"
            putExtra(EXTRA_NOTIFICATION_ID, 0)
        }
        val snoozePendingIntent: PendingIntent =
            PendingIntent.getBroadcast(this, 0, snoozeIntent, 0)
        val builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("My notification")
            .setContentText("Hello World!")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(snoozePendingIntent)
            .addAction(
                R.drawable.ic_baseline_alarm_off_24, "Snooze",
                snoozePendingIntent
            )
        with(NotificationManagerCompat.from(this)) {
            notify(notificationId, builder.build())
        }
    }

为了从通知中执行动作,我们将创建一个新的kotlin类,名称为MyBroadCastReceiverMyBroadCastReceiver 类扩展了BroadCastReceiver 接口并实现了BroadCastReceiver接口的onReceive() 方法。

通知通道

安卓8.0版本及以后的版本需要通知通道,以便在通知抽屉中显示通知。

安卓操作系统正是通过通知通道来管理通知的。在MainActivity 中创建一个名称为createNotificationChannel() 的函数,并添加下面的代码片段。

 private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "test_notification"
            val descriptionText = "test_notification_description"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
                description = descriptionText
            }
            val notificationManager: NotificationManager =
                    getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

BroadCastReceiver

在项目包中,创建一个名为MyBroadCastReceiver 的kotlin类,并添加下面的代码片段。

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent

class MyBroadCastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        //Action to be perfomed placed here
        context?.startActivity(intent)
    }

}

MainActivity 中的oncreate() 函数中添加下面的代码片段。

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        createNotificationChannel()
        btnShowNotification = findViewById(R.id.btnShowNotification)
        btnShowPendingNotification = findViewById(R.id.btnShowPendingNotification)
        btnShowActionNotification = findViewById(R.id.btnShowActionNotification)

        btnShowNotification.setOnClickListener {
            basicNotification()
        }
        btnShowPendingNotification.setOnClickListener {
            pendingNotification()
        }

        btnShowActionNotification.setOnClickListener {
            //Checks the android version
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                actionsNotification()
            }
        }
    }

用户界面

activity_main.xml 文件中添加下面的代码片段。在下面的XML设计中,有三个按钮。第一个按钮启动基本通知,第二个按钮启动待定意图通知,最后一个按钮启动行动按钮通知。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnShowNotification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Basic Notification"
        app:layout_constraintBottom_toTopOf="@+id/btnShowPendingNotification"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnShowPendingNotification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Pending Intent Notification"
        app:layout_constraintBottom_toTopOf="@+id/btnShowActionNotification"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnShowNotification" />

    <Button
        android:id="@+id/btnShowActionNotification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Action Notification"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnShowPendingNotification" />
</androidx.constraintlayout.widget.ConstraintLayout>

总结

现在你明白了通知是如何工作的,请使用Firebase云信息实现一个推送通知。