FCM 致命异常:java.lang.IllegalStateException 不允许启动服务 Intent

FCM Fatal Exception: java.lang.IllegalStateException Not allowed to start service Intent

我正在使用 'com.google.firebase:firebase-messaging:11.8.0',但一些 android 8 的设备出现此错误 java.lang.IllegalStateException 不允许启动服务意图。经过研究,我没有找到关于如何解决这个问题的明确内容。

代码:

public class FirebaseMessagesService extends FirebaseMessagingService {


public static final String FCM_ACTION_MESSAGE = "com.project.services.fcm.ACTION_MESSAGE";
public static final String EXTRA_MESSAGE = "VALUE";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    Gson gson = new Gson();
    Log.d("FCM", gson.toJson(remoteMessage.getData()));
    FirebaseMessage message = gson.fromJson(gson.toJson(remoteMessage.getData()), FirebaseMessage.class);
    Intent intent = new Intent(FCM_ACTION_MESSAGE);
    intent.setPackage("com.project");
    intent.putExtra(EXTRA_MESSAGE, message);
    startService(intent);
}

知道如何使用 FCM 在 android 8 上避免此 IllegalStateException 吗?

从android开始哦,你不能在后台启动IntentService。您需要为其创建后台服务。

除此之外,您还需要执行以下操作:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
    startForegroundService(intent)
} else {
    startService(intent);
}

onHandleIntent 中执行以下操作:

 if (Build.VERSION.SDK_INT >= 26) {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setSmallIcon(R.drawable.ic_launcher);
        mBuilder.setContentTitle("FCM Notif");
        mBuilder.setContentText("Processing notification..");
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // notificationID allows you to update the notification later on.
        mNotificationManager.notify(100, mBuilder.build());
        startForeground(100, mBuilder.mNotification);
    }