项目作者: yc86209

项目描述 :
Firebase notification with android
高级语言: Java
项目地址: git://github.com/yc86209/FirebaseNotification.git
创建时间: 2018-06-06T17:28:00Z
项目社区:https://github.com/yc86209/FirebaseNotification

开源协议:Apache License 2.0

下载


Firebase notification with android


Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost.

因版本變動過於頻繁,故紀錄使用方法及相關資訊。

Firebase

首先,你需要在 firebase 新增專案並註冊。

註冊應用程式 'com.company.mynotificantion'

下載設定檔 'google-services.json'

新增 Firebase SDK

'專案層級的 build.gradle (<專案>/build.gradle):'

  1. buildscript {
  2. dependencies {
  3. // Add this line
  4. classpath com.google.gms:google-services:4.0.1
  5. }
  6. }

'應用程式層級的 build.gradle (<專案>/<應用程式模組>/build.gradle):'

  1. dependencies {
  2. // Add this line
  3. implementation 'com.google.firebase:firebase-messaging:17.0.0'
  4. }
  5. // Add to the bottom of the file
  6. apply plugin: com.google.gms.google-services

執行應用程式以驗證是否安裝成功

Android studio

新增 FirebaseInstanceIdService

  1. public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {
  2. @Override
  3. public void onTokenRefresh() {
  4. String refreshedToken = FirebaseInstanceId.getInstance().getToken();
  5. Log.e("FCM", "refresh token:"+refreshedToken);
  6. }
  7. }

常用在單一裝置使用,只有初次安裝或者token過期才會被呼叫。

新增 FirebaseInstanceIdService

  1. public class MyFirebaseMessagingService extends FirebaseMessagingService {
  2. @Override
  3. public void onMessageReceived(RemoteMessage remoteMessage) {
  4. super.onMessageReceived(remoteMessage);
  5. Log.e("message"
  6. , Objects.requireNonNull(remoteMessage.getNotification()).getBody());
  7. Set<String> keys = remoteMessage.getData().keySet();
  8. for(String s:keys) {
  9. Log.e("fcm data:", remoteMessage.getData().get(s));
  10. }
  11. }
  12. }

App有分為前景及背景。

App state Notification Data Both
Foreground onMessageReceived onMessageReceived onMessageReceived
Background System tray onMessageReceived Notification: system tray Data: in extras of the intent.

Edit the app manifest 'AndroidManifest.xml'

  1. <service android:name=".MyFirebaseInstanceIdService">
  2. <intent-filter>
  3. <action android:name="com.google.firebase.INSTANCE_ID_EVENT" ></action>
  4. </intent-filter>
  5. </service>
  6. <service android:name=".MyFirebaseMessagingService">
  7. <intent-filter>
  8. <action android:name="com.google.firebase.MESSAGING_EVENT" ></action>
  9. </intent-filter>
  10. </service>
  11. <meta-data
  12. android:name="com.google.firebase.messaging.default_notification_icon"
  13. android:resource="@drawable/ic_stat_ic_notification" />
  14. <meta-data
  15. android:name="com.google.firebase.messaging.default_notification_color"
  16. android:resource="@color/colorAccent" />

結論

其實不難,
大概不到半小時就可以弄完,
主要還是看需求是什麼,
在經由Server發送相關Data,
其中icon除了api版本會不同之外,
還會因不同廠牌及解析度不同而異。