با Firebase Cloud Messaging شروع کنید


این راهنمای سریع نحوه راه‌اندازی Firebase Cloud Messaging را در برنامه‌های موبایل و کلاینت وب شما شرح می‌دهد تا بتوانید پیام‌ها را به طور قابل اعتمادی ارسال کنید. برای محیط‌های سرور، به بخش Your server environment and FCM مراجعه کنید.

راه‌اندازی یک برنامه کلاینت Firebase Cloud Messaging با C++

برای نوشتن برنامه کلاینت Firebase Cloud Messaging چند پلتفرمی خود با C++، از API Firebase Cloud Messaging استفاده کنید. کیت توسعه نرم‌افزار C++ برای هر دو پلتفرم اندروید و اپل کار می‌کند، و برای هر پلتفرم به برخی تنظیمات اضافی نیاز است. برای کسب اطلاعات بیشتر در مورد نحوه عملکرد کیت توسعه نرم‌افزار C++ برای iOS و اندروید با FCM ، به بخش «درک Firebase برای C++» مراجعه کنید.

فایربیس و FCM SDK را راه‌اندازی کنید

اندروید

  1. اگر هنوز Firebase را به پروژه ++C خود اضافه نکرده‌اید، آن را اضافه کنید.

    • در دستورالعمل‌های راه‌اندازی لینک‌شده، پیش‌نیازهای دستگاه و برنامه برای استفاده از Firebase C++ SDK، از جمله توصیه به استفاده از CMake برای ساخت برنامه‌تان را بررسی کنید.

    • در فایل build.gradle سطح پروژه خود، مطمئن شوید که مخزن Maven گوگل را هم در بخش‌های buildscript و هم allprojects خود وارد کرده‌اید.

  2. یک شیء Firebase App ایجاد کنید و محیط JNI و Activity را به آن ارسال کنید:

    app = ::firebase::App::Create(::firebase::AppOptions(), jni_env, activity);

  3. کلاسی تعریف کنید که رابط firebase::messaging::Listener را پیاده‌سازی کند.

  4. مقداردهی اولیه FCM ، ارسال App و یک Listener ساخته شده:

    ::firebase::messaging::Initialize(app, listener);

  5. برنامه‌هایی که به SDK سرویس‌های گوگل پلی متکی هستند، باید قبل از دسترسی به ویژگی‌ها، دستگاه را از نظر وجود APK سازگار با سرویس‌های گوگل پلی بررسی کنند. برای کسب اطلاعات بیشتر، به «بررسی APK سرویس‌های گوگل پلی» مراجعه کنید.

آی‌او‌اس+

  1. اگر هنوز Firebase را به پروژه ++C خود اضافه نکرده‌اید، آن را اضافه کنید. سپس، برای تنظیم پروژه خود برای FCM :
    1. در Podfile پروژه خود، وابستگی FCM را اضافه کنید:
      pod 'FirebaseMessaging'
    2. فریم‌ورک‌های firebase.framework و firebase_messaging.framework را از Firebase C++ SDK به پروژه Xcode خود بکشید.
  2. کلید احراز هویت APN خود را در Firebase آپلود کنید. اگر از قبل کلید احراز هویت APN ندارید، حتماً آن را در مرکز اعضای توسعه‌دهنده اپل ایجاد کنید.

    1. در داخل پروژه خود در کنسول Firebase ، نماد چرخ دنده را انتخاب کنید، تنظیمات پروژه را انتخاب کنید و سپس برگه Cloud Messaging را انتخاب کنید.

    2. در کلید احراز هویت APNs در بخش پیکربندی برنامه iOS ، روی دکمه آپلود کلیک کنید تا کلید احراز هویت توسعه یا کلید احراز هویت تولید یا هر دو را آپلود کنید. حداقل یکی از آنها لازم است.

    3. به محلی که کلید خود را ذخیره کرده‌اید بروید، آن را انتخاب کنید و روی «باز کردن» کلیک کنید. شناسه کلید را برای کلید (که در مرکز اعضای توسعه‌دهنده اپل موجود است) اضافه کنید و روی «بارگذاری» کلیک کنید.

  3. پروژه Xcode خود را برای فعال کردن اعلان‌های فوری پیکربندی کنید:

    1. پروژه را از ناحیه ناوبر انتخاب کنید.
    2. هدف پروژه را از ناحیه ویرایشگر انتخاب کنید.
    3. از قسمت ویرایشگر، برگه عمومی (General) را انتخاب کنید.

      1. به بخش Linked Frameworks and Libraries بروید، سپس برای افزودن فریم‌ورک‌ها روی دکمه + کلیک کنید.
      2. در پنجره‌ای که ظاهر می‌شود، به UserNotifications.framework بروید، روی ورودی کلیک کنید، سپس روی Add کلیک کنید.

        This framework only appears in Xcode v8 and later and is required by this library.

    4. Select the Capabilities tab from the Editor area .

      1. Switch Push Notifications to On .
      2. Scroll to Background Modes , then switch it to On .
      3. Select Remote notifications under Background Modes .
  4. Create a Firebase App object:

    app = ::firebase::App::Create(::firebase::AppOptions());

  5. Define a class that implements the firebase::messaging::Listener interface.

  6. Initialize Firebase Cloud Messaging, passing in the App and a constructed Listener:

    ::firebase::messaging::Initialize(app, listener);

Access the FCM registration token

Upon initializing the Firebase Cloud Messaging library, a registration token is requested for the client app instance. The app will receive the token with the OnTokenReceived callback, which should be defined in the class that implements firebase::messaging::Listener .

If you want to target that specific app instance, you'll need access to this token.

Note about message delivery on Android

When the app is not running at all and a user taps on a notification, the message is not, by default, routed through FCM 's built in callbacks. In this case, message payloads are received through an Intent used to start the application. To have FCM forward these incoming messages to the C++ library callback, you need to override the method onNewIntent in your Activity and pass the Intent to the MessageForwardingService .

import com.google.firebase.messaging.MessageForwardingService;

class MyActivity extends Activity {
  private static final String TAG = "MyActvity";

  @Override
  protected void onNewIntent(Intent intent) {
    Log.d(TAG, "A message was sent to this app while it was in the background.");
    Intent message = new Intent(this, MessageForwardingService.class);
    message.setAction(MessageForwardingService.ACTION_REMOTE_INTENT);
    message.putExtras(intent);
    message.setData(intent.getData());
    // For older versions of Firebase C++ SDK (< 7.1.0), use `startService`.
    // startService(message);
    MessageForwardingService.enqueueWork(this, message);
  }
}

Messages received while the app is in the background have the content of their notification field used to populate the system tray notification, but that notification content won't be communicated to FCM . That is, Message::notification will be a null.

In summary:

App state اعلان داده‌ها هر دو
پیش‌زمینه OnMessageReceived OnMessageReceived OnMessageReceived
پیشینه System tray OnMessageReceived Notification: system tray
Data: in extras of the intent.

Custom message handling on Android

By default, notifications sent to the app are passed to ::firebase::messaging::Listener::OnMessageReceived , but in some cases you may want to override the default behavior. To do this on Android you will need to write custom classes that extend com.google.firebase.messaging.cpp.ListenerService as well as update your project's AndroidManifest.xml .

Override ListenerService methods

The ListenerService is the Java class that intercepts incoming messages sent to the app and routes them to the C++ library. When the app is in the foreground (or when the app is the background and it receives a data-only payload), messages will pass through one of the callbacks provided on this class. To add custom behavior to the message handling, you will need to extend FCM 's default ListenerService :

import com.google.firebase.messaging.cpp.ListenerService;

class MyListenerService extends ListenerService {

By overriding the method ListenerService.onMessageReceived , you can perform actions based on the received RemoteMessage object and get the message data:

@Override
public void onMessageReceived(RemoteMessage message) {
  Log.d(TAG, "A message has been received.");
  // Do additional logic...
  super.onMessageReceived(message);
}

ListenerService also has a few other methods that are used less frequently. These can be overridden as well, for more information see the FirebaseMessagingService reference.

@Override
public void onDeletedMessages() {
  Log.d(TAG, "Messages have been deleted on the server.");
  // Do additional logic...
  super.onDeletedMessages();
}

@Override
public void onMessageSent(String messageId) {
  Log.d(TAG, "An outgoing message has been sent.");
  // Do additional logic...
  super.onMessageSent(messageId);
}

@Override
public void onSendError(String messageId, Exception exception) {
  Log.d(TAG, "An outgoing message encountered an error.");
  // Do additional logic...
  super.onSendError(messageId, exception);
}

Update AndroidManifest.xml

Once your custom classes have been written, they must be included in the AndroidManifest.xml to take effect. Make sure that the manifest includes the merge tools by declaring the appropriate attribute inside the <manifest> tag, like so:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.firebase.messaging.cpp.samples"
    xmlns:tools="http://schemas.android.com/tools">

In the firebase_messaging_cpp.aar archive there is an AndroidManifest.xml file which declares FCM 's default ListenerService . This manifest is normally merged with the project specific manifest which is how the ListenerService is able to run. This ListenerService needs to replaced with the custom listener service. That is accomplished by removing the default ListenerService and adding the custom Service, which can be done with the following lines your projects AndroidManifest.xml file:

<service android:name="com.google.firebase.messaging.cpp.ListenerService"
         tools:node="remove" />
<service android:name="com.google.firebase.messaging.cpp.samples.MyListenerService"
         android:exported="false">
  <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT"/>
  </intent-filter>
</service>

New versions of Firebase C++ SDK (7.1.0 onwards) use JobIntentService which requires additional modifications in AndroidManifest.xml file.

<service android:name="com.google.firebase.messaging.MessageForwardingService"
     android:permission="android.permission.BIND_JOB_SERVICE"
     android:exported="false" >
</service>

Prevent auto initialization

FCM generates a registration token for app instance targeting. When a token is generated, the library uploads the identifier and configuration data to Firebase. If you want to get an explicit opt-in before using the token, you can prevent generation at configure time by disabling FCM (and on Android, Analytics). To do this, add a metadata value to your Info.plist (not your GoogleService-Info.plist ) on Apple platforms, or your AndroidManifest.xml on Android:

اندروید

<?xml version="1.0" encoding="utf-8"?>
<application>
  <meta-data android:name="firebase_messaging_auto_init_enabled"
             android:value="false" />
  <meta-data android:name="firebase_analytics_collection_enabled"
             android:value="false" />
</application>

سویفت

FirebaseMessagingAutoInitEnabled = NO

To re-enable FCM, you can make a runtime call:

::firebase::messaging::SetTokenRegistrationOnInitEnabled(true);

This value persists across app restarts once set.

FCM allows messages to be sent containing a deep link into your app. To receive messages that contain a deep link, you must add a new intent filter to the activity that handles deep links for your app. The intent filter should catch deep links of your domain. If your messages don't contain a deep link, this configuration is not necessary. In AndroidManifest.xml:

<intent-filter>
  <action android:name="android.intent.action.VIEW"/>
  <category android:name="android.intent.category.DEFAULT"/>
  <category android:name="android.intent.category.BROWSABLE"/>
  <data android:host="CHANGE_THIS_DOMAIN.example.com" android:scheme="http"/>
  <data android:host="CHANGE_THIS_DOMAIN.example.com" android:scheme="https"/>
</intent-filter>

It is also possible to specify a wildcard to make the intent filter more flexible. For example:

<intent-filter>
  <action android:name="android.intent.action.VIEW"/>
  <category android:name="android.intent.category.DEFAULT"/>
  <category android:name="android.intent.category.BROWSABLE"/>
  <data android:host="*.example.com" android:scheme="http"/>
  <data android:host="*.example.com" android:scheme="https"/>
</intent-filter>

When users tap a notification containing a link to the scheme and host you specify, your app will start the activity with this intent filter to handle the link.

مراحل بعدی

After you have completed the setup steps, here are a few options for moving forward with FCM for C++: