Ad

Send JSON In FCM Notification Background

- 1 answer

I know tha tere are several questions about this topic, but i´m desesperate...

I´m trying to send a Serializable Object to Android phones.

The Nofitication work perfectly when the app is open, but whe is in background the notification appears but dont process it correctly, only appears the title.

the json I´m sending is:

{  


"to":"eSKuqqNvN_dkM71eJzrulCzgKn",
   "body":{           
      "mZona":"V",
      "mProvinciaCliente":"Segovia",
      "mScrapie":false,
      "mBrucelosis":false,
      "mTuberculosis":false,
      "mOtrasEnfermedades":false,
      "latitud":0.0,
      "longitud":0.0
   },
   "notification":{  
      "title":"nuevos"
   },
   "data":{  
      "mZona":"V",
      "mProvinciaCliente":"Segovia",
      "mScrapie":false,
      "mBrucelosis":false,
      "mTuberculosis":false,
      "mOtrasEnfermedades":false,
      "latitud":0.0,
      "longitud":0.0
   }
}

And the code whe i process the notification is:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String LOGTAG = "android-fcm";
    //    private static final int CANCELNOTIFICATIONID = 1;
    private Uri ordenUri;
private CamionLocationListener mlocListener;
private LocationManager mlocManager;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    UtilsVictor.appendLog("Ha llegado la notificaciíon");
    UtilsVictor.appendLog("Ha llegado la notificaciíon");

    LogVictor.d(LOGTAG, "INICIO NOTIFICACIONES");
    if (remoteMessage.getData() != null) {

        String titulo = remoteMessage.getNotification().getTitle();


        LogVictor.d(LOGTAG, "NOTIFICACION RECIBIDA");
        LogVictor.d(LOGTAG, "Título: " + titulo);
        UtilsVictor.appendLog("Título: " + titulo);
        LogVictor.d(LOGTAG, "Texto: " + texto);
        UtilsVictor.appendLog("texto: " + texto);






            generateNotificationInsertarOrden(getApplicationContext(), texto,remoteMessage.getData());


        showNotification22_10_2018(titulo, "NOTIFICACION"  , "IDo", this);
    }
}
Orden mOrden = new Orden();


private void generateNotificationInsertarOrden(Context context, String message, Map<String, String> data) {
    try{
        if(null!=message){


            Gson gson = new Gson();
            String json = gson.toJson(message);
            JSONObject jO = new JSONObject(data);
            mOrden = gson.fromJson(jO.toString(),Orden.class);


                ordenUri = insertarOrdenRecibidaEnBD(mOrden);

            Log.v("INSERTADA DE NOTCION:", mOrden.getmId() + ".");

            TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoString tareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoString = new TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoString(mOrden.getmID(), Estados.RECIBIDA);


            tareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoString.execute("");
            int icon = R.drawable.ic_launcher;
            long when = System.currentTimeMillis();
            String appname = context.getResources().getString(R.string.app_name);
            NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);

            Intent notificationIntent = new Intent(this, OrdenesOverviewActivity.class);
            notificationIntent.putExtra(MyOrdenContentProvider.CONTENT_ITEM_TYPE, ordenUri);

            notificationIntent.putExtra("ordenJSON", message);
            notificationIntent.putExtra("ESTADO",Estados.NUEVO);
            notificationIntent.putExtra("uriPasada",ordenUri);
            Notification notification;
            PendingIntent contentIntent = PendingIntent.getActivity(context,PendingIntent.FLAG_CANCEL_CURRENT,
                    notificationIntent, 0);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(
                    context);
            //  Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
            //  Uri alarmSound = Uri.parse("android.resource://" + getPackageName() + "/raw/sonidoorden.mp3");
            Uri alarmSound = Uri.parse("android.resource://es.grainsa.appmovil/"  + R.raw.sonidoorden);
            notification = builder.setContentIntent(contentIntent)
                    .setSmallIcon(icon).setTicker(appname).setWhen(0)
                    .setAutoCancel(true).setContentTitle(appname)
                    .setVibrate(new long[] {1000, 1000, 1000})
                    .setContentText("hay un NUEVO Aviso" + mOrden.getmID()).setSound(alarmSound).build();

            notificationManager.notify(0 , notification);
        }
    } catch (Exception e){



    }

}

}

How can i manage the JSON in Background???

Thank a lot for yowr answers!

Ad

Answer

There are 2 "types" of message.
Notification which has a Notification Payload/Object.
Data Message which does NOT have a Notification Obj.

When the app is in the background, if a message has a Notification, the System handles it...not your onMessageRecieved() listener.

To get data in both foreground and background, send only "Data messages" and in the app's onMessageRecieved() create the notification if one is required.

Create Notification | Android

I.e. Pass the "Notification : title" you have in the data payload instead and parse it in the onMessageRecieved() to create the Notification.

iOS users always require a notification payload when the app is in the background to trigger the app "message recieved" listener. In this case for my work, I collect firebase tokens and the platform (iOS/Android/Web) and treat each accordingly when sending Pushes.

Ad
source: stackoverflow.com
Ad