首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在android中使用FCM自定义推送通知

要在Android应用中使用Firebase Cloud Messaging(FCM)自定义推送通知,请按照以下步骤操作:

  1. 添加Firebase项目 如果您还没有在Firebase控制台中创建项目,请访问https://console.firebase.google.com/并创建一个新项目。
  2. 将Android应用添加到项目中 在Firebase控制台中,选择您刚刚创建的项目,然后单击"添加应用"按钮。按照向导将您的Android应用添加到项目中。
  3. 添加Firebase SDK到您的项目 要将Firebase SDK添加到您的Android项目,请按照以下步骤操作:
    • 打开Android Studio项目。
    • 确保已将项目依赖项中指定的Firebase库添加到app build.gradle文件中。
    • 同步Gradle。
  4. 请求权限 要接收推送通知,您需要在您的应用的AndroidManifest.xml文件中申明权限。在<manifest>标签内添加以下行: <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
  5. 创建服务 要处理来自FCM的消息,请创建一个服务类,该类继承自FirebaseMessagingService。在您的应用代码中添加以下代码: import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MyFirebaseMessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); // Handle your custom notification here. } }
  6. 在AndroidManifest.xml中声明服务 在AndroidManifest.xml中的<application>标签内添加以下代码: <service android:name=".MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
  7. 创建通知渠道 对于Android Oreo(API级别26)及更高版本,您需要为通知创建一个通知渠道。在您的应用代码中添加以下代码: private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.channel_name); String description = getString(R.string.channel_description); int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel("channel_id", name, importance); channel.setDescription(description); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } } 并在您的 onCreate() 方法中调用 createNotificationChannel()
  8. 自定义通知 要自定义推送通知,请在 onMessageReceived() 方法中创建一个 RemoteMessage.Notification 对象,然后使用 NotificationCompat.Builder 构建自定义通知。例如: @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); RemoteMessage.Notification notification = remoteMessage.getNotification(); if (notification != null) { Intent intent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id") .setContentTitle(notification.getTitle()) .setContentText(notification.getBody()) .setSmallIcon(R.mipmap.ic_launcher_round) .setContentIntent(pendingIntent) .setAutoCancel(true); NotificationManagerCompat manager = NotificationManagerCompat.from(this); manager.notify(0, builder.build()); } }

现在,在向您的应用程序发送推送通知后,您应该会看到自定义通知。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券