当应用被杀死时,FCM onMessageReceived不会触发(Android Oreo)

时间:2020-03-02 18:52:26

标签: java android

我正在使用需要在发送FCM消息时打开前台服务的应用程序。我的代码是: FirebaseService.class:

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.io.IOException;

public class FirebaseService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d("From",remoteMessage.getFrom());
        Intent intt = new Intent(this,foreground.class);
        startActivity(intt);
    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        String channelId = "TT";
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .setContentTitle("TR")
                        .setContentText(messageBody)
                        .setAutoCancel(true);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }
        Log.d("TEST","received");
        Server server = new Server();
        try {
            if(server.connect())
                Log.d("TEST","Connected");
            else
                Log.d("TEST","NOT Connected");

        } catch (Exception e) {
            e.printStackTrace();
        }
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

}

但是当我发送一条消息时,它会向我显示另一个通知(不是我在函数中创建的消息),其中包含消息发送时发送的消息正文和标题(在我的函数中,我没有发送标题和从收到的邮件正文中,我只放了一些随机文本)。而且我的前台类没有被解雇。

1 个答案:

答案 0 :(得分:0)

我不确定,但是我遇到了几乎相同的问题,并要求用户授予

ACTION_MANAGE_OVERLAY_PERMISSION

解决了我的问题。之后,前台类被解雇了。

Restrictions on starting activities from the background