如何用Firebase在Android中实现数据库驱动的推送通知

404 阅读5分钟

用Firebase在Android中实现数据库驱动的推送通知

当你想给用户提供关于你的应用产品的相关信息时,推送通知会很有帮助。

以一个处理发放和偿还贷款的应用为例。如果用户在付款时没有得到所付金额、余额和其他相关信息的通知,这将是一种糟糕的用户体验。

在本教程中,我们将深入了解如何根据Firebase的实时数据库变化来发送Push通知。

前提条件

要继续学习,你应该具备以下条件。

  • 在你的机器上安装了Android Studio。
  • 具有创建和运行Android应用程序的良好知识。
  • Kotlin编程语言和Viewbinding的基本知识。
  • Firebase云功能的基础知识。
  • Firebase实时数据库的基本了解。
  • 在你的机器上安装Node.js和Firebase CLI。

什么是推送通知?

显示在用户的网络浏览器、手机或桌面电脑中的信息被称为推送通知。企业用它们来向客户传达及时的公告、交易和其他信息。只要用户连接到互联网或打开手机或浏览器,就可以从任何地方获得这些信息。

我们什么时候需要它们?

推送通知通过允许用户接收来提供便利。

  • 即时收到交易收据 - 推广产品或优惠以促进销售。
  • 体育比赛成绩和新闻显示在他们的锁屏上 - 公共设施通知,如交通、天气和滑雪雪的报告显示在他们的锁屏上。
  • 提高客户满意度。
  • 关于航班登记、变更和转机的信息。

在你的Firebase控制台,创建一个新的Firebase项目,并确保你已将支付计划改为Blaze。

第1步 - 创建一个云函数

在我们跳入Android Studio之前,让我们先写一个云函数,每次在实时数据库中创建新数据时都会被触发。

到你的桌面上,创建一个新的文件夹。给它起一个你选择的名字。

在你的终端中打开它,键入以下命令。

  • firebase-login - 用你的Google账户登录到Firebase。

firebase login

  • firebase-init - 初始化一个Firebase项目。

firebase init

选择你要为这个项目配置的功能--Firebase功能。

firebase feature

  • 对于下一步,选择一个现有的项目,并选择你在Firebase控制台中创建的项目。
  • 然后选择Javascript 作为你要使用的语言。
  • 接下来,允许使用ESLint。
  • 在这一步,点击Y ,用npm安装依赖。

就这样,Firebase初始化完成了。

用你喜欢的代码编辑器打开这个文件夹,例如VsCode、Atom或Sublime Text。

在函数目录内,打开index.js ,写下以下触发代码。

const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp();

exports.databaseDrivenPushNotifs = functions.database.ref('/payment/{paymentId}').onCreate(
    (snapshot, context) => {
        admin.database().ref('/device_token').once('value').then(allTokens =>{
            if(allTokens.val()){
                console.log("Token available");
                const token = Object.keys(allTokens.val());
                console.log(token)
                admin.messaging().sendToDevice(token, 
                    {
                        notification: {
                            title: "Payment Received",
                            body: "Dear customer your payment has been received, kindly wait for your balance to update"
                        }
                    }
                );
            }else{
                console.log("Token not available")
            }
        });
    }
);

该函数使用实时数据库模块并监听/payment 的引用。当一个新的带有paymentId 的付款被创建时,这个函数被触发。

在该函数中,我们读取存储在数据库中的设备令牌,并使用sendToDevice 方法通知设备。

请根据你的需要自由地定制这个函数。

一旦你完成了函数的编写,是时候部署它了。

firebase deploy --only functions

deploy function

如果你的函数部署成功了,打开你的Firebase控制台,导航到函数部分,你应该看到已经部署的函数。

function

第2步 - 开始使用Android studio

打开Android Studio,创建一个空的Android项目。

一旦应用程序被创建,将其链接到你在Firebase控制台创建的项目。

第3步 - 添加必要的依赖项

在你的应用级build.gradle ,添加以下依赖项。

// Firebase functions
implementation 'com.google.firebase:firebase-functions:20.0.1'

// Firebase messaging
implementation 'com.google.firebase:firebase-messaging:20.2.1'

// Firebase Realtime database
implementation platform('com.google.firebase:firebase-bom:29.0.4')
implementation 'com.google.firebase:firebase-database'

第4步 - 设计用户界面

创建一个简单的用户界面,包含两个EditText,一个用于输入名字,另一个用于输入金额。同时,包括一个Button ,当用户将数据保存在数据库中时,会触发通知。你可以设计一个与此类似的布局。

layout

第5步 - 创建一个通知服务

创建一个名为NotificationService 的新类,该类扩展了FirebaseMessagingService 。一旦应用程序首次启动,该类将在数据库中存储设备令牌。另外,当收到消息时,它将显示一个通知。

private const val CHANNEL_ID = "myChannel"

class NotificationService : FirebaseMessagingService() {

    override fun onNewToken(newToken: String) {
        super.onNewToken(newToken)
        val tokenMap = HashMap<String, String>()
        tokenMap["token"] = newToken

        FirebaseDatabase.getInstance().getReference("device_token").child(newToken)
            .setValue(tokenMap)
    }

    @SuppressLint("UnspecifiedImmutableFlag")
    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)

        val title = message.notification?.title
        val body = message.notification?.body

        val notificationManager =
            getSystemService((Context.NOTIFICATION_SERVICE)) as NotificationManager
        val notificationID = Random.nextInt()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel(notificationManager)
        }

        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(title)
            .setContentText(body)
            .setSmallIcon(R.drawable.ic_baseline_notifications_24)
            .setAutoCancel(true)
            .build()

        notificationManager.notify(notificationID, notification)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel(notificationManager: NotificationManager) {
        val channelName = "channelName"
        val channel = NotificationChannel(CHANNEL_ID, channelName, IMPORTANCE_HIGH).apply {
            description = "My channel description"
            enableLights(true)
            lightColor = Color.GREEN
        }

        notificationManager.createNotificationChannel(channel)
    }
}

在你的AndroidManifest.xml ,包括Service ,并添加以下动作。

<action android:name="com.google.firebase.MESSAGING_EVENT" />

第6步 - 触发通知

在你的MainActivity 类中,在onCreate 方法中,设置一个onClickListenerButton 。这将把在EditTexts 中输入的数据保存到数据库中。

binding.buttonPay.setOnClickListener {
    val name = binding.edtName.text.toString()
    val amount = binding.edtAmount.text.toString()

    if (name.isEmpty() || amount.isEmpty()) {
        return@setOnClickListener
    }

    val userDataMap = HashMap<String, String>()
    userDataMap["name"] = name
    userDataMap["amount"] = amount

    FirebaseDatabase.getInstance().getReference("payment").push().setValue(userDataMap)

    Toast.makeText(this, "Data saved", Toast.LENGTH_SHORT).show()
}

演示

当你运行应用程序并保存一些数据时,你应该收到一个被触发的通知,因为一些数据已经被保存在/payment 参考。

demo

总结

有了这些,你现在对数据库驱动的推送通知有了更好的理解,如何编写触发推送通知的云函数,创建一个简单的Android应用,在实时数据库中保存数据,并在数据被保存时收到通知。