FirebaseMessagingService仅在后台显示通知

时间:2017-11-10 08:20:16

标签: android notifications firebase-cloud-messaging

FCM消息可以包含datanotification或两者之一。系统使用notification生成的通知缺少功能,因此我删除了notification并仅发送了data。因此,我必须自己创建通知。

创建和显示通知很简单,但我不希望在我的应用程序(特别是MainActivity,但它只有一个活动,无论如何)已经在前台时显示通知。大多数应用程序在前台时都不会显示通知。

我如何知道onMessageReceived我的应用是否不在前台?

class MessagingService : FirebaseMessagingService()
{
    override fun onMessageReceived(remoteMessage: RemoteMessage?)
    {
        // Check if message contains a data payload.
        if (remoteMessage?.data?.isNotEmpty() == true)
        {
            //Log.d(TAG, "Message data payload: " + remoteMessage.data)

            ......

            if "Only when my app is on the background or not running?"
                sendNotification("Got a message.")
        }
    }

1 个答案:

答案 0 :(得分:2)

/**
 * Method checks if the app is in background or not
 *
 * @param context Application context
 * @return True/False
 */
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;
}