【问题标题】:Bring app to foreground when receiving GCM Push notification (Cordova)接收 GCM 推送通知时将应用程序置于前台 (Cordova)
【发布时间】:2017-01-24 15:54:07
【问题描述】:

我在 Cordova 中使用最新的 GCM 推送通知插件。通知运行良好,但我希望应用程序在用户收到推送通知时显示在前台。

我从很多地方尝试了几种解决方案,但我仍然无法在收到通知时让应用程序进入前台。

似乎有人在这里做了类似的事情,但无论我做什么我都无法复制成功:

Bring cordova application to foreground when push arrives

他的问题中 GCMIntentService.java 的代码与现在可用的代码不同。

我怎样才能让它工作?

【问题讨论】:

标签: android cordova notifications gcmlistenerservice


【解决方案1】:

在 GCMIntentservice.java 文件的 onMessageReceived 方法中加入以下行。

@Override
    public void onMessageReceived(String from, Bundle extras) {
        Log.d(LOG_TAG, "onMessage - from: " + from);

        if (extras != null) {
            Context applicationContext = getApplicationContext();

            SharedPreferences prefs = applicationContext.getSharedPreferences(PushPlugin.COM_ADOBE_PHONEGAP_PUSH, Context.MODE_PRIVATE);
            boolean forceShow = prefs.getBoolean(FORCE_SHOW, false);
            boolean clearBadge = prefs.getBoolean(CLEAR_BADGE, false);

            extras = normalizeExtras(applicationContext, extras);

            if (clearBadge) {
                PushPlugin.setApplicationIconBadgeNumber(getApplicationContext(), 0);
            }

            // if we are in the foreground and forceShow is `false` only send data
            if (!forceShow && PushPlugin.isInForeground()) {
                Log.d(LOG_TAG, "foreground");
                extras.putBoolean(FOREGROUND, true);
                extras.putBoolean(COLDSTART, false);
                PushPlugin.sendExtras(extras);
            }
            // if we are in the foreground and forceShow is `true`, force show the notification if the data has at least a message or title
            else if (forceShow && PushPlugin.isInForeground()) {
                Log.d(LOG_TAG, "foreground force");
                extras.putBoolean(FOREGROUND, true);
                extras.putBoolean(COLDSTART, false);

                showNotificationIfPossible(applicationContext, extras);
            }
            // if we are not in the foreground always send notification if the data has at least a message or title
            else {
                Log.d(LOG_TAG, "background");
                extras.putBoolean(FOREGROUND, false);

                Intent wintent = new Intent(context, MainActivity.class);
            wintent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(wintent);

                extras.putBoolean(COLDSTART, PushPlugin.isActive());

                showNotificationIfPossible(applicationContext, extras);
            }
        }
    }

并确保您导入 MainActivity.java

【讨论】:

  • 感谢您的回复。我刚才是这样做的,并通过输入代码“import MainActivity;”来导入 MainActivity。虽然它仍然没有将应用程序带到最前面......只是在标准推送消息中通知推送。还有其他想法吗?
猜你喜欢
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
  • 2016-01-16
  • 1970-01-01
相关资源
最近更新 更多