Ionic / Cordova应用程序不会在后台接收推送通知

问题描述 投票:4回答:3

我的Android应用程序在后台没有收到推送通知,它应该根据documentation

Android设备上的Android应用程序无需运行即可接收消息。只要应用程序设置了正确的广播接收器和权限,系统就会在消息到达时通过Intent广播唤醒Android应用程序。

尝试不同的通知发现它确实在关闭时收到推送通知,当且仅当通知包含属性“message”时,如果没有,它只是丢弃它。 (推送通知只是JSON对象)。

我的通知包含所有类型的属性,包括“alert”,“id”和“title”,但只有“message”才能让Android唤醒应用。

示例通知不起作用:

{ event: 'message',
  from: '947957531940',
  collapse_key: 'do_not_collapse',
  foreground: true,
  payload: 
   { alert: 'Mensaje de Prueba',
     title: 'Titulo Mensaje de Prueba' } }

有效的示例通知:

{ event: 'message',
  from: '947957531940',
  message: 'Contenido del mensaje de prueba.',
  collapse_key: 'do_not_collapse',
  foreground: true,
  payload: 
   { alert: 'Mensaje de Prueba',
     title: 'Titulo Mensaje de Prueba',
     message: 'Contenido del mensaje de prueba.' } }

这是Android标准设计还是我在我的应用程序中做错了什么?

我的应用程序是使用Ionic与Cordova开发的。

PD:请原谅我的英语。

编辑:

这是app.js中.run模块内的Android推送代码,因为ng-cordova指令指定:

if (ionic.Platform.isAndroid()){

  var androidConfig = {
    "senderID": "94*************",
    "ecb": "window.casosPush"
  };

  try{
    var pushNotification = window.plugins.pushNotification;
  } catch (ex){

  }

  // Llamada en caso de exito
  var successfn = function(result){
    //alert("Success: " + result);
  };

  // Llamada en caso de error
  var errorfn   = function(result){
    window.alert("Error: " + result);
  };

  // Llamada de casos de notificacion push
  window.casosPush = function(notification){
    switch (notification.event){
      case 'registered':
        if (notification.regid.length > 0){
          $rootScope.data.token = notification.regid;
          //alert('registration ID = ' + notification.regid);
        }
      break;

      case 'message':

        $rootScope.mensajes.unshift(notification.payload);
        $localstorage.setArray('mensajes', $rootScope.mensajes);
        alert(JSON.stringify(notification));
      break;

      case 'error':
        alert('GCM error = ' + notification.msg);
      break;

      default:
        alert('An unknown GCM event has occurred');
      break;
    }
  };
  try{

    // Llamada de registro con la plataforma GCM 
    pushNotification.register(successfn,errorfn,androidConfig);
  } catch(notification){

  }
}
android cordova push-notification ionic-framework phonegap-plugins
3个回答
7
投票

在涉及Cordova / Phonegap推送插件的stackoverflow中搜索所有问题后,我找到了问题的来源。写在插件的源代码中,它不应该。

问题是插件源代码要求推送通知具有“消息”字段,以便在后台触发通知。它在GCMIntentService.java文件中指定。

if (extras.getString("message") != null && extras.getString("message").length() != 0) {
    createNotification(context, extras);
}

最有用的帖子是这个answer和插件库中的issue。所以,因为我没有权力推送服务器操作,我无法在推送通知中指定“消息”字段,我别无选择,只能重写源代码。

所以我重写了这样的代码:

@Override
protected void onMessage(Context context, Intent intent) {
    Log.d(TAG, "onMessage - context: " + context);

    // Extract the payload from the message
    Bundle extras = intent.getExtras();
    if (extras != null)
    {
        // if we are in the foreground, just surface the payload, else post it to the statusbar
        if (PushPlugin.isInForeground()) {
            extras.putBoolean("foreground", true);
            PushPlugin.sendExtras(extras);
        }
        else {
            extras.putBoolean("foreground", false);

            // Send a notification if there is a message
            //if (extras.getString("message") != null && extras.getString("message").length() != 0) {
            if (extras.getString("alert") != null && extras.getString("alert").length() != 0) {
                createNotification(context, extras);
            }
        }
    }
}

这样,如果插件收到带有“alert”字段而不是“message”字段的推送通知,则会触发本地通知。

然后,我更改了本地通知本身的代码:

public void createNotification(Context context, Bundle extras)
{
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String appName = getAppName(this);

        Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        notificationIntent.putExtra("pushBundle", extras);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        int defaults = Notification.DEFAULT_ALL;

        if (extras.getString("defaults") != null) {
            try {
                defaults = Integer.parseInt(extras.getString("defaults"));
            } catch (NumberFormatException e) {}
        }

        NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(context)
                .setDefaults(defaults)
                .setSmallIcon(context.getApplicationInfo().icon)
                .setWhen(System.currentTimeMillis())
                //.setContentTitle(extras.getString("title"))
                .setContentTitle(extras.getString("alert"))
                //.setTicker(extras.getString("title"))
                .setTicker(extras.getString("alert"))
                .setContentIntent(contentIntent)
                .setAutoCancel(true);
    /*
        String message = extras.getString("message");
        if (message != null) {
            mBuilder.setContentText(message);
        } else {
            mBuilder.setContentText("<missing message content>");
        }
    */
    // Agregado mensaje predefinido
    mBuilder.setContentText("Haz clic para más información");

        String msgcnt = extras.getString("msgcnt");
        if (msgcnt != null) {
            mBuilder.setNumber(Integer.parseInt(msgcnt));
        }

        int notId = 0;

        try {
            notId = Integer.parseInt(extras.getString("notId"));
        }
        catch(NumberFormatException e) {
            Log.e(TAG, "Number format exception - Error parsing Notification ID: " + e.getMessage());
        }
        catch(Exception e) {
            Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage());
        }

        mNotificationManager.notify((String) appName, notId, mBuilder.build());
    }

现在,通知栏中的通知将首先显示字段“alert”而不是“title”,其次是预定义消息,而不是我的推送通知中不存在的字段“message”。

然后我只需重新编译代码:

ionic platform rm android

ionic platform add android

ionic run android

所以孩子们,这就是当你为每个人写一个插件时会发生什么,但你不考虑通用案例,而且你没有很好地记录。该插件仅对推送通知中包含“消息”和“标题”字段的用户有用。

因为这个原因,我失去了两天的实习机会,我花了很多时间写这篇文章,以便其他人不必这样做。


2
投票

你是对的@David prieto。问题是插件源代码要求推送通知具有“消息”字段,以便在后台触发通知。

有一种方法可以将“消息”字段放在推送通知中并且简单。具有通知数据的有效载荷数组,通过API发送。它应该有一个“消息”字段。因此推送通知将自动在其中包含一个消息字段,它将在后台和前台检测到。


0
投票

我有同样的问题,我通过更改一些代码行解决了。我使用了phonegap-plugin-push插件并更改了这个文件。(仅适用于android平台)

插件文件夹:phonegap-plugin-push / src / android / com / adobe / phonegap / push / FCMService.java

平台文件夹:android / src / com / adobe / phonegap / push / FCMService.java

您需要更改两个文件中的一个,这取决于您是否已添加平台。

  // 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);
    extras.putBoolean(COLDSTART, PushPlugin.isActive());
    showNotificationIfPossible(applicationContext, extras);
  }

这里,PushPlugin.sendExtras(),这是localNotification的触发器,showNotificationIfPossible()是电话通知的触发器。

所以我改变了这样的代码。

  // 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);  // commented   }   
  // 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);// commented   }   
  // 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);
    extras.putBoolean(COLDSTART, PushPlugin.isActive());
    //showNotificationIfPossible(applicationContext, extras); // commented   
 }   
 PushPlugin.sendExtras(extras); //added

所以我可以根据需要获取通知并使用localNotification插件处理它。希望这会帮助你。

© www.soinside.com 2019 - 2024. All rights reserved.