当前位置: 首页 > 知识库问答 >
问题:

应用被终止/刷出时未收到FCM推送通知

傅志诚
2023-03-14

我正在将通知从GCM迁移到FCM。在GCM中,当应用程序处于前台、后台或被杀死时,我能够收到通知,但在FCM中,当应用程序未被打开或被刷出时,我无法收到通知。我错过什么了吗????

    <service
        android:name=".Services.ExtendedInstanceIDListenerService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
    <service
        android:name=".Services.FcmMessageHandler"           
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
@Override
public void onMessageReceived(RemoteMessage message) {

    // Check if message contains a data payload.
    if (message.getData().size() > 0) {
        Log.d("ABC", "Message data payload: " + message.getData());
    }

sendNotification("test");
}

 private void sendNotification(String message) {

 Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(getNotificationIcon())
                .setColor(getResources().getColor(R.color.button_background))
                //.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon))
                .setContentTitle("App")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                .setDefaults(Notification.DEFAULT_ALL)
                .setPriority(Notification.PRIORITY_MAX)
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
        Notification notification = notificationBuilder.build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

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

        notificationManager.notify(notificationNumber /* ID of notification */, notification);

}

private int getNotificationIcon() {
    boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
    return useWhiteIcon ? R.drawable.ic_notification : R.drawable.ic_launcher;
}

}

json请求正文:

{
  "notification":{
     "title":"Title",
     "message":"Message.",
     "icon" = "ic_notification",
     "sound" = "default",
     "click_action":"FCM_PLUGIN_ACTIVITY"
  },
  "data":{
     "title":"Title",
     "message":"Message.",
     "icon" = "ic_notification",
     "sound" = "default"
  },
    "to":"chIFk6ljlfdskfdsifosdifnodsifnsdofindsofindsfoindsifvndsnmdkslakjdn2p",
    "priority":"high"
}

共有1个答案

艾宁
2023-03-14
private void showNotificationMessage(Context context, String title, String message, Intent intent) {
    notificationUtils = new NotificationUtils(context);
    //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    intent.putExtra("message", message);
    //intent.putExtra("notification", "noti");
    notificationUtils.showNotificationMessage(title, message, intent);
}

/**
 * Showing notification with text and image
 */
private void showNotificationMessageWithBigImage(Context context, String title, String message, Intent intent, String imageUrl) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    intent.putExtra("message", message);
    //intent.putExtra("notification", "noti");
    notificationUtils.showNotificationMessage(title, message, intent, imageUrl);
}

试试这个。我是这样做的。使用NotificationUtils。下面是NotificationUtils代码

  package com.fourever.imlogistic.Utility;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.text.Html;
import android.text.TextUtils;
import android.util.Patterns;

import com.fourever.imlogistic.R;
import com.fourever.imlogistic.misc.Config;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;




/**
 * Created by Ravi on 31/03/15.
 */
public class NotificationUtils {

    private static String TAG = NotificationUtils.class.getSimpleName();

    private Context mContext;

    public NotificationUtils(Context mContext) {
        this.mContext = mContext;
    }

    public void showNotificationMessage(String title, String message, Intent intent) {
        showNotificationMessage(title, message, intent, null);
    }

    public void showNotificationMessage(final String title, final String message, Intent intent, String imageUrl) {
        // Check for empty push message
        if (TextUtils.isEmpty(message))
            return;


        // notification icon
        final int icon = R.drawable.logo;

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        final PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        mContext,
                        0,
                        intent,
                        PendingIntent.FLAG_CANCEL_CURRENT
                );

        final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                mContext);

        final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                + "://" + mContext.getPackageName() + "/raw/notification");

        if (!TextUtils.isEmpty(imageUrl)) {

            if (imageUrl != null && imageUrl.length() > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) {

                Bitmap bitmap = getBitmapFromURL(imageUrl);

                if (bitmap != null) {
                    showBigNotification(bitmap, mBuilder, icon, title, message, resultPendingIntent, alarmSound);
                } else {
                    showSmallNotification(mBuilder, icon, title, message, resultPendingIntent, alarmSound);
                }
            }
        } else {
            showSmallNotification(mBuilder, icon, title, message, resultPendingIntent, alarmSound);
            playNotificationSound();
        }
    }


    private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, PendingIntent resultPendingIntent, Uri alarmSound) {

        NotificationCompat.BigTextStyle inboxStyle = new NotificationCompat.BigTextStyle();

        //inboxStyle.addLine(message);

        Notification notification;
        notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
                .setAutoCancel(true)
                .setContentTitle(title)
                .setContentIntent(resultPendingIntent)
                .setSound(alarmSound)
                .setStyle(inboxStyle.bigText(message))
                .setSmallIcon(R.drawable.app_icon)
                .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                .setContentText(message)
                .build();

        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(Config.NOTIFICATION_ID, notification);
    }

    private void showBigNotification(Bitmap bitmap, NotificationCompat.Builder mBuilder, int icon, String title, String message, PendingIntent resultPendingIntent, Uri alarmSound) {
        NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
        bigPictureStyle.setBigContentTitle(title);
        bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
        bigPictureStyle.bigPicture(bitmap);
        Notification notification;
        notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
                .setAutoCancel(true)
                .setContentTitle(title)
                .setContentIntent(resultPendingIntent)
                .setSound(alarmSound)
                .setStyle(bigPictureStyle)
                .setSmallIcon(R.drawable.app_icon)
                .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                .setContentText(message)
                .build();

        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(Config.NOTIFICATION_ID_BIG_IMAGE, notification);
    }

    /**
     * Downloading push notification image before displaying it in
     * the notification tray
     */
    public Bitmap getBitmapFromURL(String strURL) {
        try {
            URL url = new URL(strURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // Playing notification sound
    public void playNotificationSound() {
        try {
            Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                    + "://" + mContext.getPackageName() + "/raw/notification");
            Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound);
            r.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Method checks if the app is in background or not
     */
    public static boolean isAppIsInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }

    // Clears notification tray messages
    public static void clearNotifications(Context context) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
    }

    public static long getTimeMilliSec(String timeStamp) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = format.parse(timeStamp);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

使用isAppIsInBackground方法代码。这对你有帮助

 类似资料:
  • 即使应用程序从后台被杀死或从内存中被刷出,我如何接收到设备的fcm通知。我使用维梧、Oppo、松下设备。但在应用程序被终止时未收到通知。

  • 我使用的是FCM云消息,当应用程序在后台但未被杀死或应用程序正在运行时,它工作得很好。一旦应用程序被停止或从最近的应用程序杀死,它不会收到任何通知。 即使是在应用程序启动后,它也不会收到旧的消息。 用于发送通知的服务器端代码 firebase服务和通知的清单代码 感谢任何帮助。

  • 当我的应用程序前台服务被终止时,不会收到FCM通知,更清楚的是,我正试图让我的应用程序始终在后台运行,我使用前台服务来实现这一点,有时应用程序未被ANDROID系统终止,前台通知会出现15个多小时,但其他情况下,当我的前台通知被终止,并且我发送FCM通知时,它在1小时或更短时间内被终止,而我的设备没有收到FCM通知!!这里有什么问题!我怎样才能解决它!

  • 我使用firebase推送通知到设备令牌。当应用程序打开或前景我可以得到通知很好。但当当前任务的应用程序被杀死或清除应用程序时,我无法收到通知发送。 我试过OnMessageReceedEardy的第一次工作。但现在它不工作时,杀死的应用程序。 > 代码接收通知:

  • 我正在开发一个电子邮件应用程序,我希望用户在收到新电子邮件后立即收到推送通知。为此,我使用FCM。我刚刚通过以下链接尝试使用FCM推送通知:https://www.youtube.com/watch?v=XijS62iP1Xo 感谢每一种帮助。提前感谢。

  • 我创建了一个简单的聊天应用程序,在接收者离线时向他发送推送通知。 正如我在标题中所说,当应用程序被终止时,我无法通过推送通知正确传递消息。实际上,当iPhone接收到推送通知并且应用程序被终止时,甚至application:didReceiveMemoteNotification:fetchCompletionHandler也不会被触发(如其他示例和apple文档中所示)。 然而,我的应用程序与W