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

时间:2018-04-11 21:48:14

标签: java android firebase push-notification android-8.0-oreo

我正在使用'com.google.firebase:firebase-messaging:11.8.0'但是有些设备使用android 8会出现此错误java.lang.IllegalStateException不允许启动服务Intent。经过研究,我没有找到解决这个问题的明确方法。

代码:

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吗?

1 个答案:

答案 0 :(得分:2)

从android O开始,你无法在后台启动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);
    }