要在Android应用中使用Firebase Cloud Messaging(FCM)自定义推送通知,请按照以下步骤操作:
build.gradle
文件中。<manifest>
标签内添加以下行:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WAKE_LOCK" /><application>
标签内添加以下代码:
<service android:name=".MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>onCreate()
方法中调用 createNotificationChannel()
。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()); } }现在,在向您的应用程序发送推送通知后,您应该会看到自定义通知。
领取专属 10元无门槛券
手把手带您无忧上云