我正在关注Android上设置Firebase Cloud Messaging客户端应用程序的教程,该应用程序涉及将<service>
组件添加到AndroidManifest.xml
。
<service android:name=".java.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
但是,我得到了Unresolved class MyFirebaseMessagingService
。我到底从哪里导入该课程?
注意:我正在Kotlin写作
在您提供的相同链接上,提到您需要在项目中添加服务类并在AndroidManifest.xml中声明它:
<service android:name=".java.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
基本上这些是您需要遵循的步骤:
- 在您的软件包内保存Java类,创建一个名为
MyFirebaseMessagingService
的类(您可以选择任何名称) - 如上图所示,在
AndroidManifest.xml
中声明。 您在上面步骤1中定义的此类将扩展
FirebaseMessagingService
,因此它将具有一种称为onMessageReceived
的方法,您必须覆盖,如下所示:@Override public void onMessageReceived(RemoteMessage remoteMessage) { // ... // TODO(developer): Handle FCM messages here. Log.d(TAG, "From: " + remoteMessage.getFrom()); // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { Log.d(TAG, "Message data payload: " + remoteMessage.getData()); if (/* Check if data needs to be processed by long running job */ true) { // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher. scheduleJob(); } else { // Handle message within 10 seconds handleNow(); } } // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. }
如果您是在Kotlin中编写代码,则需要将您的类命名为MyFireBaseMessagingService.kt,然后创建一个类并放在代码下方。该链接本身也提到了这一点。
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
// ...
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "From: ${remoteMessage?.from}")
// Check if message contains a data payload.
remoteMessage?.data?.isNotEmpty()?.let {
Log.d(TAG, "Message data payload: " + remoteMessage.data)
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob()
} else {
// Handle message within 10 seconds
handleNow()
}
}
// Check if message contains a notification payload.
remoteMessage?.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.body}")
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}