این راهنمای سریع نحوه راهاندازی Firebase Cloud Messaging را در برنامههای موبایل و کلاینت وب شما شرح میدهد تا بتوانید پیامها را به طور قابل اعتمادی ارسال کنید. برای محیطهای سرور، به بخش Your server environment and FCM مراجعه کنید.
یک برنامه کلاینت Firebase Cloud Messaging با Unity راهاندازی کنید
برای نوشتن برنامه کلاینت Firebase Cloud Messaging چند پلتفرمی خود با Unity، از Firebase Cloud Messaging API استفاده کنید. Unity SDK هم برای اندروید و هم برای اپل کار میکند، البته برای هر پلتفرم به تنظیمات اضافی نیاز است.
قبل از اینکه شروع کنی
پیشنیازها
Unity 2021 LTS یا بالاتر را نصب کنید. پشتیبانی از Unity 2020 منسوخ شده تلقی میشود و پس از انتشار نسخه اصلی بعدی، دیگر به طور فعال پشتیبانی نخواهد شد. نسخههای قبلی نیز ممکن است سازگار باشند، اما به طور فعال پشتیبانی نخواهند شد.
(فقط پلتفرمهای اپل) موارد زیر را نصب کنید:
- Xcode نسخه ۱۳.۳.۱ یا بالاتر
- کوکو پادز ۱.۱۲.۰ یا بالاتر
مطمئن شوید که پروژه یونیتی شما این الزامات را برآورده میکند:
- برای iOS - iOS 13 یا بالاتر را هدف قرار میدهد.
- برای tvOS - tvOS 13 یا بالاتر را هدف قرار میدهد
- برای اندروید - سطح API 21 (لالیپاپ) یا بالاتر را هدف قرار میدهد
یک دستگاه راهاندازی کنید یا از یک شبیهساز برای اجرای پروژه Unity خود استفاده کنید.
برای iOS یا tvOS - یک دستگاه فیزیکی برای اجرای برنامه خود تنظیم کنید و این کارها را انجام دهید:
- یک کلید احراز هویت اعلانهای فوری اپل برای حساب توسعهدهنده اپل خود دریافت کنید.
- اعلانهای فوری را در XCode از طریق مسیر App > Capabilities فعال کنید.
برای اندروید - شبیهسازها باید از یک تصویر شبیهساز با Google Play استفاده کنند.
- با استفاده از حساب گوگل خود وارد فایربیس شوید .
اگر از قبل پروژه یونیتی ندارید و فقط میخواهید یکی از محصولات فایربیس را امتحان کنید، میتوانید یکی از نمونههای شروع سریع ما را دانلود کنید.
مرحله ۱: ایجاد یک پروژه Firebase
قبل از اینکه بتوانید Firebase را به پروژه Unity خود اضافه کنید، باید یک پروژه Firebase ایجاد کنید تا به پروژه Unity شما متصل شود. برای کسب اطلاعات بیشتر در مورد پروژههای Firebase، به بخش «درک پروژههای Firebase» مراجعه کنید.
مرحله ۲: برنامه خود را در Firebase ثبت کنید
شما میتوانید یک یا چند برنامه یا بازی را برای اتصال به پروژه Firebase خود ثبت کنید.
به کنسول Firebase بروید.
در مرکز صفحه نمای کلی پروژه، روی آیکون Unity (
) کلیک کنید تا گردش کار راهاندازی شود.اگر قبلاً برنامهای به پروژه Firebase خود اضافه کردهاید، برای نمایش گزینههای پلتفرم، روی «افزودن برنامه» کلیک کنید.
کدام هدف ساخت پروژه Unity خود را که میخواهید ثبت کنید، انتخاب کنید، یا حتی میتوانید انتخاب کنید که هر دو هدف را همزمان ثبت کنید.
شناسه(های) مختص پلتفرم پروژه یونیتی خود را وارد کنید.
برای iOS — شناسه iOS پروژه Unity خود را در فیلد شناسه بسته iOS وارد کنید.
برای اندروید — شناسه اندروید پروژه یونیتی خود را در فیلد نام بسته اندروید وارد کنید.
اصطلاحات نام بسته و شناسه برنامه اغلب به جای یکدیگر استفاده میشوند.
پروژه یونیتی خود را در Unity IDE باز کنید، سپس به بخش تنظیمات مربوط به هر پلتفرم بروید:
برای iOS — به تنظیمات ساخت > iOS بروید.
برای اندروید — به اندروید > تنظیمات پخشکننده > سایر تنظیمات بروید.
شناسه پروژه Unity شما، مقدار شناسه بسته (Bundle Identifier) است (به عنوان مثال، شناسه:
com.yourcompany.yourproject
).(اختیاری) نام مستعار مخصوص پلتفرم پروژه یونیتی خود را وارد کنید.
این نامهای مستعار، شناسههای داخلی و راحتی هستند و فقط در کنسول Firebase برای شما قابل مشاهده هستند.روی ثبت برنامه کلیک کنید.
مرحله 3: اضافه کردن فایلهای پیکربندی Firebase
فایل(های) پیکربندی Firebase مخصوص پلتفرم خود را در گردش کار تنظیم کنسول Firebase دریافت کنید.
برای iOS — روی دانلود GoogleService-Info.plist کلیک کنید.
برای اندروید — روی دانلود google-services.json کلیک کنید.
فایل پیکربندی Firebase حاوی شناسههای منحصر به فرد اما غیر محرمانه برای پروژه و برنامه شما است. برای کسب اطلاعات بیشتر در مورد این فایل پیکربندی، به بخش «درک پروژههای Firebase» مراجعه کنید.
شما میتوانید فایل پیکربندی Firebase خود را در هر زمانی دوباره دانلود کنید.
مطمئن شوید که نام فایل پیکربندی با کاراکترهای اضافی مانند
(2)
ضمیمه نشده باشد.
پنجره پروژه Unity خود را باز کنید، سپس فایل (های) پیکربندی خود را به پوشه
Assets
منتقل کنید.به کنسول Firebase برگردید، در گردش کار تنظیمات، روی Next کلیک کنید.
مرحله 4: اضافه کردن SDK های Firebase Unity
در کنسول Firebase ، روی دانلود Firebase Unity SDK کلیک کنید، سپس SDK را در جایی مناسب از حالت فشرده خارج کنید.
شما میتوانید هر زمان که بخواهید Firebase Unity SDK را دوباره دانلود کنید.
کیت توسعه نرمافزار (SDK) Firebase Unity مختص پلتفرم خاصی نیست.
در پروژه باز Unity خود، به مسیر Assets > Import Package > Custom Package بروید.
از SDK استخراجشده، محصولات پشتیبانیشدهی Firebase را که میخواهید در برنامهی خود استفاده کنید، انتخاب کنید.
برای تجربه بهینه با Firebase Cloud Messaging ، توصیه میکنیم Google Analytics در پروژه خود فعال کنید . همچنین، به عنوان بخشی از راهاندازی Analytics ، باید بسته Firebase را برای Analytics به برنامه خود اضافه کنید.
Analytics فعال شد
- پکیج Firebase را برای Google Analytics اضافه کنید:
FirebaseAnalytics.unitypackage
- بستهی Firebase Cloud Messaging اضافه کنید:
FirebaseMessaging.unitypackage
Analytics فعال نیست
بستهی Firebase Cloud Messaging اضافه کنید:
FirebaseMessaging.unitypackage
- پکیج Firebase را برای Google Analytics اضافه کنید:
در پنجرهی «وارد کردن بستهی یونیتی» ، روی «وارد کردن» کلیک کنید.
به کنسول Firebase برگردید، در گردش کار تنظیمات، روی Next کلیک کنید.
مرحله ۵: الزامات نسخه سرویسهای گوگل پلی را تأیید کنید
برخی از محصولات موجود در Firebase Unity SDK برای اندروید به Google Play services نیاز دارند. بدانید کدام محصولات این وابستگی را دارند . Google Play services باید قبل از استفاده از این محصولات بهروز باشند.
دستور using
و کد مقداردهی اولیه زیر را در ابتدای برنامه خود اضافه کنید. میتوانید قبل از فراخوانی هر متد دیگری در SDK Google Play services را بررسی کرده و در صورت تمایل، آنها را به نسخه مورد نیاز بهروزرسانی کنید.
using Firebase.Extensions;
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
var dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available) {
// Create and hold a reference to your FirebaseApp,
// where app is a Firebase.FirebaseApp property of your application class.
app = Firebase.FirebaseApp.DefaultInstance;
// Set a flag here to indicate whether Firebase is ready to use by your app.
} else {
UnityEngine.Debug.LogError(System.String.Format(
"Could not resolve all Firebase dependencies: {0}", dependencyStatus));
// Firebase Unity SDK is not safe to use here.
}
});
پروژه Unity شما برای استفاده از Firebase ثبت و پیکربندی شده است.
Get setup with Apple platforms
Use the following instructions to set up FCM with Unity and Apple platforms.
Upload your APNs authentication key
Upload your APNs authentication key to Firebase. If you don't already have an APNs authentication key, make sure to create one in the Apple Developer Member Center .
Inside your project in the Firebase console, select the gear icon, select Project Settings , and then select the Cloud Messaging tab.
In APNs authentication key under iOS app configuration , click the Upload button to upload your development authentication key, or production authentication key, or both. At least one is required.
Browse to the location where you saved your key, select it, and click Open . Add the key ID for the key (available in the Apple Developer Member Center ) and click Upload .
Enable push notifications on Apple platforms
- Click your project in Xcode, then select the General tab from the Editor area .
- Scroll to Linked Frameworks and Libraries , then click the + button to add a framework.
- In the window that appears, scroll to UserNotifications.framework , click that entry, then click Add .
- Click your project in Xcode, then select the Capabilities tab from the Editor area .
- Switch Push Notifications to On .
- Scroll to Background Modes , then switch it to On .
- Select the Remote notifications checkbox under Background Modes .
Initialize Firebase Cloud Messaging
The Firebase Cloud Message library will be initialized when adding handlers for either the TokenReceived
or MessageReceived
events.
Upon initialization, a registration token is requested for the client app instance. The app will receive the token with the OnTokenReceived
event, which should be cached for later use. You'll need this token if you want to target this specific device for messages.
In addition, you will need to register for the OnMessageReceived
event if you want to be able to receive incoming messages.
The setup will look like this:
public void Start() { Firebase.Messaging.FirebaseMessaging.TokenReceived += OnTokenReceived; Firebase.Messaging.FirebaseMessaging.MessageReceived += OnMessageReceived; } public void OnTokenReceived(object sender, Firebase.Messaging.TokenReceivedEventArgs token) { UnityEngine.Debug.Log("Received Registration Token: " + token.Token); } public void OnMessageReceived(object sender, Firebase.Messaging.MessageReceivedEventArgs e) { UnityEngine.Debug.Log("Received a new message from: " + e.Message.From); }
Get setup with Android platforms
Use the following instructions to setup FCM with Unity and Android platforms.
Configure an Android entry point Activity
Firebase Cloud Messaging comes bundled with a custom entry point activity that replaces the default UnityPlayerActivity
. If you are not using a custom entry point, this replacement happens automatically and you shouldn't have to take any additional action.
The Firebase Cloud Messaging Unity Plugin on Android comes bundled with two additional files:
-
Assets/Plugins/Android/libmessaging_unity_player_activity.jar
contains an activity calledMessagingUnityPlayerActivity
that replaces the standardUnityPlayerActivity
. -
Assets/Plugins/Android/AndroidManifest.xml
instructs the app to useMessagingUnityPlayerActivity
as the entry point to the app.
These files are provided because the default UnityPlayerActivity
does not handle onStop
, onRestart
activity lifecycle transitions or implement the onNewIntent
which is necessary for Firebase Cloud Messaging to correctly handle incoming messages.
Configure a custom entry point Activity
If your app does not use the default UnityPlayerActivity
you will need to remove the supplied AndroidManifest.xml
and make sure that your custom activity properly handles all transitions of the Android Activity Lifecycle (an example of how to do this is shown below). If your custom activity extends UnityPlayerActivity
you can instead extend com.google.firebase.MessagingUnityPlayerActivity
which implements all necessary methods.
If you are using a custom Activity and not extending com.google.firebase.MessagingUnityPlayerActivity
, you should include the following snippets in your Activity.
/** * Workaround for when a message is sent containing both a Data and Notification payload. * * When the app is in the background, if a message with both a data and notification payload is * received the data payload is stored on the Intent passed to onNewIntent. By default, that * intent does not get set as the Intent that started the app, so when the app comes back online * it doesn't see a new FCM message to respond to. As a workaround, we override onNewIntent so * that it sends the intent to the MessageForwardingService which forwards the message to the * FirebaseMessagingService which in turn sends the message to the application. */ @Override protected void onNewIntent(Intent intent) { Intent message = new Intent(this, MessageForwardingService.class); message.setAction(MessageForwardingService.ACTION_REMOTE_INTENT); message.putExtras(intent); message.setData(intent.getData()); // For earlier versions of Firebase C++ SDK (< 7.1.0), use `startService`. // startService(message); MessageForwardingService.enqueueWork(this, message); } /** * Dispose of the mUnityPlayer when restarting the app. * * This makes sure that when the app starts up again it does not start with stale data. */ @Override protected void onCreate(Bundle savedInstanceState) { if (mUnityPlayer != null) { mUnityPlayer.quit(); mUnityPlayer = null; } super.onCreate(savedInstanceState); }
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>
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.
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 . This means that FirebaseMessage.Notification
will be a null.
به طور خلاصه:
App state | اعلان | دادهها | هر دو |
---|---|---|---|
پیشزمینه | Firebase.Messaging.FirebaseMessaging.MessageReceived | Firebase.Messaging.FirebaseMessaging.MessageReceived | Firebase.Messaging.FirebaseMessaging.MessageReceived |
پیشینه | System tray | Firebase.Messaging.FirebaseMessaging.MessageReceived | Notification: system tray Data: in extras of the intent. |
Handling messages with deep links on Android
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. 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.
Prevent auto initialization
FCM generates a registration token for device 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). You can add a metadata value to your Info.plist
(not your GoogleService-Info.plist
) on Apple, 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.FirebaseMessaging.TokenRegistrationOnInitEnabled = true;
This value persists across app restarts once set.
مراحل بعدی
After you have completed the setup steps, here are a few options for moving forward with FCM for Unity: