应用关闭或被杀时未收到 Android FCM 通知

Posted

技术标签:

【中文标题】应用关闭或被杀时未收到 Android FCM 通知【英文标题】:Android FCM notification is not received when app is close or Killed 【发布时间】:2021-04-06 08:02:14 【问题描述】:

我实现了 FCM 推送通知。主要问题是当应用程序关闭时,在设备上发生这种情况时通知不会到达。 我为此尝试了很多方法;当通知以“成功”发送服务器响应时,但我从未收到。

public class MyFirebaseMessagingService extends FirebaseMessagingService 
    private static final String CHANNEL_NAME = "FCM";
    private static final String CHANNEL_DESC = "Firebase Cloud Messaging";
    final String TAG = "MyFirebaseMsgService";
    private String id = "";
    private String title = "";
    private String message = "";
    private String type = "";
    private String module = "";
    private String fcm_notification = "";

    @Override
    public void onNewToken(String s) 
        super.onNewToken(s);
        Log.e("newToken", s);
        getSharedPreferences("_", MODE_PRIVATE).edit().putString("fb", s).apply();
    

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) 
        super.onMessageReceived(remoteMessage);
        Log.d(TAG, "Message Body" + remoteMessage.getNotification().getBody());
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) 
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            id = remoteMessage.getData().get("id");
            title = remoteMessage.getData().get("title");
            message = remoteMessage.getData().get("message");
            type = remoteMessage.getData().get("type");
            fcm_notification = "Y";
        

        sendNotification(remoteMessage.getNotification().getBody(), id, title, message, type, fcm_notification);
    


    private void sendNotification(String body, String user_id, String title, String message, String type, String fcm_notification) 

        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("fcm_notification", fcm_notification);
        intent.putExtra("title", title);
        intent.putExtra("message", message);
        intent.putExtra("type", type);
        intent.putExtra("id", user_id);

        int uniqueInt = (int) (System.currentTimeMillis() & 0xff);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), uniqueInt, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "");
        notificationBuilder.setSmallIcon(R.drawable.ic_launcher_background)
                .setContentText(body)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setColor(getResources().getColor(R.color.colorAccent))
                .setLights(Color.RED, 1000, 300)
                .setDefaults(Notification.DEFAULT_VIBRATE)
                .setSmallIcon(R.mipmap.ic_launcher);

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
            NotificationChannel channel = new NotificationChannel(
                    getString(R.string.notification_channel_id), CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT
            );
            channel.setDescription(CHANNEL_DESC);
            channel.setShowBadge(true);
            channel.canShowBadge();
            channel.enableLights(true);
            channel.setLightColor(Color.RED);
            channel.enableVibration(true);
            channel.setVibrationPattern(new long[]100, 200, 300, 400, 500);

            assert notificationManager != null;
            notificationManager.createNotificationChannel(channel);
        

        assert notificationManager != null;
        notificationManager.notify(0, notificationBuilder.build());
    

    public static String getToken(Context context) 
        return context.getSharedPreferences("_", MODE_PRIVATE).getString("fb", "empty");
    

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.TestNotification"
    android:targetSandboxVersion="1">
  
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:name=".Utils.App"
        android:allowBackup="true"
        android:icon="@drawable/kl_logo"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">

        <service
            android:name=".Utils.ForegroundService"
            android:enabled="true"
            android:exported="true"/>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".Utils.MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/notification_channel_id" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@mipmap/ic_launcher" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />

    </application>

</manifest>

【问题讨论】:

【参考方案1】:

尝试将 enabled="true" 和 INTERNAL_SERVICE 权限添加到您的消息服务

【讨论】:

还是不行先生.....给我一些其他的解决方案

以上是关于应用关闭或被杀时未收到 Android FCM 通知的主要内容,如果未能解决你的问题,请参考以下文章

系统刚启动时未收到 FCM 通知

使用 react-native-firebase 在 Android 中关闭应用程序时未收到 fcm 消息

通过 FCM 发送时未收到推送通知,但在 IOS 上通过 APN 发送时收到

应用程序被杀时,一个通知多个意图

Android - 包含 click_action 后未收到 FCM 推送通知

应用关闭时未收到 Android 推送通知