首页 文章

收到GCM推送通知(Cordova)时将应用程序带到前台

提问于
浏览
1

我正在使用Cordova的最新GCM推送通知插件 . 通知工作正常,但我希望应用程序在用户收到推送通知时到达前台 .

我已经尝试了很多地方的几个解决方案,但是当收到通知时我仍然无法使应用程序到达前台 .

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

Bring cordova application to foreground when push arrives

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

我怎样才能让它发挥作用?

1 回答

  • 0

    在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

相关问题