使用Firebase云消息传递在Android中推送通知

本文详细介绍了如何使用Firebase云消息传递在Android应用中实现推送通知。首先解释了推送通知的概念和作用,然后阐述了如何设置Firebase项目,并逐步指导读者添加依赖、获取设备令牌、创建服务以接收和显示通知。通过这个教程,读者将学会使用Firebase为Android应用添加推送通知功能。
摘要由CSDN通过智能技术生成

这篇文章介绍了如何在Android中发送推送通知 。 过去,我们曾经使用Google Cloud消息传递服务在Android中发送推送通知。 最近,它引入了一种使用Firebase发送推送数据的新方法。 即使基本原理保持不变,Firebase还是引入了一些有趣的新功能。 Firebase支持其他服务,例如:

  • 认证方式
  • 远程配置
  • 崩溃报告

这篇文章将逐步介绍如何从Firebase控制台向应用程序发送推送通知。

什么是推送通知?

在深入研究如何在Android中发送通知的细节之前,弄清什么是推送通知很有用。 使用Android推送通知,我们的应用可以将新事件通知用户。 即使我们的应用程序不在前台运行,也会发生这种情况。 使用此服务,我们可以在发生新事件时将数据从服务器发送到我们的应用程序。 保持连接到服务器(拉方法)以询问是否有新事件,这种范例的效率要高得多。

使用推送通知,我们可以使用户了解事件,而不会耗尽智能手机的电池。 当用户收到通知时,该通知将作为自定义图标显示在状态栏中。 发送推送通知时可以使用不同的范例:

消息到单个设备

给主题的消息(向订阅了特定主题的多个设备发送相同的消息。这实现了模型发布者/订阅者)

发送给群组的消息(多个设备共享用于识别智能手机的相同密钥)

android_push_notification_firebase-1024x512

设置Firebase云消息传递项目

现在是时候开始了! 创建一个帐户以访问Firebase控制台并定义一个项目:

android_firebase_create_new_project

然后:

android_firebase_project

创建项目后,必须添加应用程序的程序包名称。 请注意,在Android Studio和Firebase控制台中使用相同的程序包名称:

create_android_firebase_app

在此过程结束时,将在Firebase上配置您的项目,并准备开发Android应用程序。 最后,您将获得一个必须在应用程序模块级别复制的json文件。

如何使用Firebase实施Android推送通知

现在,我们可以开发与Firebase集成的Android应用。 第一步,我们必须将Firebase添加到我们的应用程序并修改gradle文件。 在项目级别,让我们将gradle fille修改为:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

并使用模块名称(通常命名为app):

....
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.google.firebase:firebase-messaging:9.4.0'
}

apply plugin: 'com.google.gms.google-services'

在这种情况下,我们添加了消息传递依赖性。 一旦配置了gradle文件,下一步就是创建我们的应用程序。 在MainActivity我们添加一个Button以获取当前token 。 此令牌很重要,因为我们在Firebase控制台中使用它来设置正确的目标设备。
让我们假设,我们已经在Activity类中定义了包含按钮的布局:

Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      String tkn = FirebaseInstanceId.getInstance().getToken();
      Toast.makeText(MainActivity.this, "Current token ["+tkn+"]",
                     Toast.LENGTH_LONG).show();
      Log.d("App", "Token ["+tkn+"]");
     }
   });
 }

请注意,我们使用FirebaseInstanceId单例来获取当前实例,然后获取当前令牌。 生成令牌可能需要一段时间,因此您可以在开始时获取一个空值。
此外,我们可以使用扩展FirebaseInstanceIdService的自定义服务来监视令牌创建过程,并在令牌可用时得到通知。 在这种情况下,我们重写onTokenRefresh方法。

public class FireIDService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
        String tkn = FirebaseInstanceId.getInstance().getToken();
        Log.d("Not","Token ["+tkn+"]");

    }
}

在这种方法中,我们只记录令牌,但是它可以在真实应用中用于将令牌发送到服务器,以便服务端将其存储。
不要忘记在Manifest.xml声明此服务。

.. 
<service
     android:name=".FireIDService">
     <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
     </intent-filter>
 </service>

最后,我们实现了处理传入的推送通知的服务:

public class FireMsgService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d("Msg", "Message received ["+remoteMessage+"]");

        // Create Notification
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410, 
                        intent, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder notificationBuilder = new
                 NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_name)
                .setContentTitle("Message")
                .setContentText(remoteMessage.getNotification().getBody())
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);
    }
}

onMessageReceived方法中,我们仅显示包含已发送消息的通知。
运行该应用程序,我们将在以下视频中显示结果:

在本文的最后,您了解了如何在带Firebase的Android中使用推送通知。

翻译自: https://www.javacodegeeks.com/2016/09/push-notification-android-using-firebase-cloud-messaging.html

使用Firebase应用内消息传递可以让你的Android应用实现实时通信和消息推送功能。下面是一些步骤来帮助你在Android应用上使用Firebase应用内消息传递: 1. 首先,在Firebase控制台创建一个新的Firebase项目,并在项目设置启用Firebase Cloud Messaging服务。 2. 在你的Android应用,添加Firebase Core和Firebase Cloud Messaging依赖项。你可以通过Gradle文件来添加这些依赖项,例如: ``` implementation 'com.google.firebase:firebase-core:17.2.1' implementation 'com.google.firebase:firebase-messaging:20.0.0' ``` 3. 在你的AndroidManifest.xml文件添加以下代码以注册Firebase Cloud Messaging服务: ``` <service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> ``` 4. 创建一个MyFirebaseMessagingService类并继承FirebaseMessagingService。在这个类,你可以处理接收到的消息并执行相应的操作,例如: ``` public class MyFirebaseMessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { // 处理接收到的消息 String message = remoteMessage.getData().get("message"); // 执行相应的操作 } } ``` 5. 最后,在你的应用发送消息,你可以使用Firebase Cloud Messaging API来发送消息,例如: ``` FirebaseMessaging.getInstance().send(new RemoteMessage.Builder("SENDER_ID" + "@gcm.googleapis.com") .setMessageId(Integer.toString(msgId.incrementAndGet())) .addData("message", "这是一条测试消息") .build()); ``` 以上是在Android应用上使用Firebase应用内消息传递的一些基本步骤,你可以根据你的需求进行相关的配置和定制化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值