应用程序打开时不显示通知

2024-03-11

应用程序运行时不显示通知。 当应用程序关闭时它会起作用。

MyFirebaseMessagingService.java

    public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

    private NotificationUtils notificationUtils;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)
            return;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getNotification().getBody());
        }

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);
        PrefManager.setStringPreferences ( Constants.REGID, token );
        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
//        sendRegistrationToServer(token);
    }

    private void handleNotification(String message) {
        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        }else{
            // If the app is in background, firebase itself handles the notification
        }
    }

    private void handleDataMessage(JSONObject json) {
        Log.e(TAG, "push json: " + json.toString());

        try {
            JSONObject data = json.getJSONObject("data");

            String title = data.getString("title");
            String message = data.getString("message");
            boolean isBackground = data.getBoolean("is_background");
            String imageUrl = data.getString("image");
            String timestamp = data.getString("timestamp");
            JSONObject payload = data.getJSONObject("payload");

            Log.e(TAG, "title: " + title);
            Log.e(TAG, "message: " + message);
            Log.e(TAG, "isBackground: " + isBackground);
            Log.e(TAG, "payload: " + payload.toString());
            Log.e(TAG, "imageUrl: " + imageUrl);
            Log.e(TAG, "timestamp: " + timestamp);


            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent( Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", message);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
                notificationUtils.playNotificationSound();

//                if (TextUtils.isEmpty(imageUrl)) {
//                    showNotificationMessage(getApplicationContext(), title, message, timestamp, pushNotification);
//                } else {
//                    // image is present, show notification with image
//                    showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, pushNotification, imageUrl);
//                }
            } else {
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(), HomeActivity.class);
                resultIntent.putExtra("message", message);

                // check for image attachment
                if (TextUtils.isEmpty(imageUrl)) {
                    showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
                } else {
                    // image is present, show notification with image
                    showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }


      //Showing notification with text only

    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
    }


     //Showing notification with text and image

    private void showNotificationMessageWithBigImage(Context context,String title,String message,String timeStamp,Intent intent,String imageUrl) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
    }
}

In handleDataMessage()当应用程序不在后台时我放置代码showNotificationMessage()。但是当我把showNotificationMessage()通知功能不显示应用程序是后台还是前台。

当我评论时,功能通知会出现,但仅当应用程序处于后台时才会出现。

如何在应用程序处于前台时显示通知?


默认情况下,仅当应用程序不在前台时才会显示通知。

如果您想在应用程序位于前台时在托盘中显示通知,请添加自定义方法以使用NotificationCompat.Builder显示通知

并在 onMessageReceived 中调用该方法,例如

if (remoteMessage.getNotification() != null){
    Log.d(TAG, "Objects: " + remoteMessage.getNotification());
    generateNotification(getApplicationContext(),remoteMessage.getNotification().getBody());
}

这是方法

private void generateNotification(Context context, String msg) {

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

        String channelId = "channel-fbase";
        String channelName = "demoFbase";
        int importance = NotificationManager.IMPORTANCE_HIGH;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(
                    channelId, channelName, importance);
            notificationManager.createNotificationChannel(mChannel);
        }

        Intent notificationIntent = new Intent(getApplicationContext(), AboutActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mBuilder.setSmallIcon(R.mipmap.ic_launcher);
            int color = 0x008000;
            mBuilder.setColor(color);
        } else {
            mBuilder.setSmallIcon(R.mipmap.ic_launcher);
        }
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(msg));

        mBuilder.setContentTitle(msg);
        mBuilder.setContentText(msg);
        mBuilder.setContentIntent(pendingIntent);


        //If you don't want all notifications to overwrite add int m to unique value
        Random random = new Random();
        int m = random.nextInt(9999 - 1000) + 1000;
        mNotificationManager.notify(m, mBuilder.build());
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

应用程序打开时不显示通知 的相关文章

  • 尝试在 Android 上使用 FFMPEG。编译但是还是不行

    首先 我尝试使用 ffmpeg 将图像数组编译成 Android 上的视频 我已经遵循了各种在线教程 并且已经能够编译 Android 的库 但仍然需要项目运行 我现在使用的存储库可以在这里找到 https github com Batte
  • Android ImageButton 在 Activity 中运行良好。它在片段中不起作用

    我正在尝试转换布局 使其包含片段 其中一个视图是具有侦听器的 ImageButton 该代码作为 Activity 运行良好 但作为 Fragment 会出现麻烦 第一个问题是我无法使用 findViewById 但我能够在这里找到答案并使
  • 有没有办法有一个屏蔽数字输入字段?

    我正在 Android 上创建一个 HTML5 应用程序 对于这个特定场景 我们有一个用于信用卡安全代码的输入字段 我们希望强制输入字段仅包含数字并被屏蔽 我没有运气搜索这个特定的案例 从我自己研究 尝试中可以看出 这不能纯粹通过 HTML
  • Kotlin 数据类中的函数作为参数会导致解析错误

    我有一个 Kotlin 帽子中的数据类正在使用 Parcelize注释以方便分割 问题是我现在想将一个函数传递给此类 但我真的不知道如何使该函数在打包过程中不被考虑 这是我的数据类 Parcelize data class GearCate
  • Android HTTP-post AsyncHttpClient

    public void postLoginData AsyncHttpClient myClient new AsyncHttpClient RequestParams params1 new RequestParams params1 p
  • Android:对于具有 LinearLayout 定义的成员的 ListView,上下文菜单不显示?

    我有一个 ListActivity 和 ListView 并且我已将一些数据绑定到它 数据显示得很好 而且我还为视图注册了一个上下文菜单 当我将列表项显示为简单的 TextView 时 它工作正常
  • 检查从 arrayadapter 获取的复选框

    我有标题清单 CheckBox 我想控制默认检查哪一个 所以我试图获得正确的视图并检查它 但由于某种原因它不起作用 知道为什么吗 form checkbox item xml
  • 如何在 Android 应用程序中使用 xmlserializer 创建 xml

    您好 我正在制作一个预订应用程序 我需要在创建 xml 后将 xml 发送到服务器 如何使用创建 xmlxmlserializer创建后将其发送到服务器 http api ean com ean services rs hotel v3 l
  • 为什么 Android Eclipse 不断刷新外部文件夹并花费很长时间?

    我只有一部新的 Android 手机 我一直在修补一些基本的应用程序 每当我保存任何内容时 Eclipse 的 Android 插件就会刷新外部文件夹 这让我抓狂 通常我不会介意 但当需要 10 秒才能刷新时 我开始注意到 我已经搜索过 其
  • overridePendingTransition 显示第二个活动的速度太快

    我有 2 个活动 我想在两个活动之间创建一个动画过渡 以便两个活动的视图向上滑动 就好像第二个活动正在向上推动第一个活动一样 在我的第一个活动中我使用 Intent iSecondActivity new Intent FirstActiv
  • Android Studio,工具提示消失得这么快

    我有以下问题 我想从这个工具提示中复制错误文本 但是一旦我将鼠标悬停在它上面 它就消失得如此之快 这让我发疯 我有以下 android studio 版本 我有以下设置 谢谢您的帮助 如果有人遇到这个问题 这与logcat刷新的方式有关 每
  • 在 Android Studio 中运行重建项目后会发生什么?

    该文件http www jetbrains com idea help rebuilding project html search reb http www jetbrains com idea help rebuilding proje
  • 如何使用Multipart将图像上传到php服务器

    我一直很头疼 如何将图像上传到服务器 这对我来说是新任务 但对我来说很困惑 我在 stackoverflow 上搜索并用谷歌搜索 但我遇到了问题 我的意图是从 SD 卡上传照片并从相机拍照并上传到服务器 在ios中 这个任务已经完成 在io
  • Swift - 本地通知不会被触发

    我正在 Swift 3 中编码 我只是想发送通知now没有任何延迟或间隔 然而 通知永远不会被触发 这是我的代码 视图控制器代码 import UserNotifications class HomeViewController UIVie
  • 从前台服务的活动中释放内存

    我有一个带有前台服务和一项活动的应用程序 该服务可以在启动时自行启动 也可以从 Activity 中启动 我注意到当服务在启动时自行启动时 内存使用量约为 3MB 一旦我打开该 Activity 内存使用量就会跃升至约 9mB 一旦 Act
  • python 和 android 中通过 AES 算法加密和解密

    我有用于 AES 加密的 python 和 android 代码 当我在android中加密文本时 它在python上成功解密 但无法在android端解密 有人有想法吗 Python代码 import base64 import hash
  • 允许的 APNS 持续连接数量是多少?

    我正在尝试编写服务器端代码来为我的应用程序发送推送通知 根据 Apple 的建议 我计划保留连接并根据需要发送推送通知 Apple 还允许打开和保留多个并行连接以发送推送通知 您可以与同一网关或多个网关实例建立多个并行连接 为此 我想维护一
  • 找不到R类

    当我打开 Eclipse 时 R class在我的项目中消失了 为什么 我有 eclipse juno 和最新版本的 android SDK The R class不会重新生成 因为代码中有错误 我怎么解决这个问题 Try Project
  • Android Webview:无法调用确定的可见性() - 从未见过 pid 的连接

    我有一个 Android Webview 当我单击链接下载文件 pdf 图像等 时 我收到一条错误消息 Error message Cannot call determinedVisibility never saw a connectio
  • SubscriptionManager 用于读取运行 Android 5.1+ 的双 SIM 设备的 IMSI

    对于 API 22 我尝试使用 SubscriptionManager 读取双 SIM 卡 IMSI IMSI 是 14 到 15 个字符 格式如下 MCC MNC MSIN MCC 移动国家 地区代码 例如 美国为 310 MNC 移动网

随机推荐