You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Oreo下Firebase Cloud Messaging服务无法运行问题求助

Fixing FCM Push Notifications on Android Oreo+ When App is Closed

Hey there! I’ve dealt with this exact headache when updating chat apps for Android Oreo, so I know how annoying it is when push notifications stop working once the app’s closed. Let’s walk through the fixes step by step:

1. Understand FCM Message Types & Oreo’s Restrictions

First, let’s clarify the core issue: Android 8.0 (API 26+) imposed strict limits on unrestricted background services to save battery. So if you’re using data messages (messages that require your app’s code to handle them), your old background service approach won’t work anymore.

  • Notification Messages: These are handled directly by the Android system’s notification tray—they’ll show up even if your app is closed, as long as the device is online. If you’re not seeing these, double-check your FCM console/server configuration.
  • Data Messages: These need your app to process them, so we need a system-compliant way to handle them in the background.

2. Replace Background Services with JobIntentService

JobIntentService is Google’s recommended replacement for background services on Oreo+. It automatically uses JobScheduler on API 26+ (which respects battery optimizations) and falls back to a regular Service on older versions.

Steps to Implement:

  • Create a class extending JobIntentService:
    class FCMDataMessageService : JobIntentService() {
        companion object {
            private const val JOB_ID = 1001
            fun enqueueWork(context: Context, work: Intent) {
                enqueueWork(context, FCMDataMessageService::class.java, JOB_ID, work)
            }
        }
    
        override fun onHandleWork(intent: Intent) {
            // Handle your data message logic here
            // Example: Parse the data and show a custom notification
            val data = intent.extras
            data?.let {
                val title = it.getString("title")
                val body = it.getString("body")
                showNotification(title, body)
            }
        }
    
        private fun showNotification(title: String?, body: String?) {
            // Don't forget to create a NotificationChannel first (see step 3)
            val notificationBuilder = NotificationCompat.Builder(this, "CHAT_CHANNEL_ID")
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(title)
                .setContentText(body)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true)
    
            val notificationManager = NotificationManagerCompat.from(this)
            notificationManager.notify(System.currentTimeMillis().toInt(), notificationBuilder.build())
        }
    }
    
  • Register the service in your AndroidManifest.xml:
    <service
        android:name=".FCMDataMessageService"
        android:permission="android.permission.BIND_JOB_SERVICE" />
    
  • In your FirebaseMessagingService’s onMessageReceived method, enqueue the work instead of starting a background service:
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        if (remoteMessage.data.isNotEmpty()) {
            // Handle data messages via JobIntentService
            val intent = Intent(this, FCMDataMessageService::class.java)
            intent.putExtras(remoteMessage.data as Bundle)
            FCMDataMessageService.enqueueWork(this, intent)
        } else {
            // Handle notification messages (system takes care of these)
        }
    }
    

3. Create a Notification Channel (Mandatory for Oreo+)

Android Oreo+ requires all notifications to be tied to a channel. If you skip this, your custom notifications won’t show up at all. Add this code when your app starts (e.g., in your Application class or main Activity):

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val channel = NotificationChannel(
        "CHAT_CHANNEL_ID",
        "Chat Notifications",
        NotificationManager.IMPORTANCE_HIGH
    ).apply {
        description = "Notifications for new chat messages"
        enableVibration(true)
        vibrationPattern = longArrayOf(100, 200, 300)
    }
    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    notificationManager.createNotificationChannel(channel)
}

4. Set High Priority for FCM Messages

For data messages to be delivered promptly (even when the app is closed), set the priority to high on the server side. For example, if using the Firebase Admin SDK:

// Node.js example
admin.messaging().send({
    data: {
        title: "New Message",
        body: "Hey, how are you?"
    },
    token: "DEVICE_TOKEN",
    android: {
        priority: "high"
    }
});

Important Note: Forced App Stop

If a user manually force-stops your app (via Settings > Apps > Your App > Force Stop), Android blocks all background processes for your app—there’s no way around this. You can add a small note in your app’s settings or onboarding to tell users not to force-stop it if they want to receive messages.

内容的提问来源于stack exchange,提问作者user5511158

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:13:24