1

Tengo una consulta... Como puedo capturar una notificacion push en un textview o en una lista ... aquí esta mi código

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    edit = (EditText) findViewById(R.id.edit);
    button = (Button) findViewById(R.id.butt);
   send = (Button) findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            token = FirebaseInstanceId.getInstance().getToken();
            edit.setText(token);
        }
    });
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            GetDataFromEditText();
            SendData(data);
        }
    });

}
public void GetDataFromEditText(){
        data = edit.getText().toString();
        Toast.makeText(MainActivity.this,data,Toast.LENGTH_LONG).show();
    }
public void SendData(final String token) {
    class PostData extends AsyncTask<String,Void,String>{
        @Override
        protected String doInBackground(String... params) {
            String tokenHoldre = token;
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
           // nameValuePairs.add(new BasicNameValuePair("tokenfirebase", tokenHoldre));
            nameValuePairs.add(new BasicNameValuePair("fcm_token", tokenHoldre));
          //  nameValuePairs.add(new BasicNameValuePair("idcliente", "08366"));
        //    nameValuePairs.add(new BasicNameValuePair("esregistro", "1"));
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(ServerURL);
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
            } catch (ClientProtocolException e) {

            } catch (IOException e) {

            }
            return "Success..";
        }
        protected void onPostExecute(String result) {

            super.onPostExecute(result);

            Toast.makeText(MainActivity.this, "Success..", Toast.LENGTH_LONG).show();
        }
    }
    PostData sendPostReqAsyncTask = new PostData();
   sendPostReqAsyncTask.execute(token);
}

Aqui esta mi callback:

   @Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if(remoteMessage.getData().size() >0){
        type="json";
        sendNotificatio(remoteMessage.getData().toString());
    }
    if(remoteMessage.getNotification() !=null) {
        type = "message";
        sendNotificatio(remoteMessage.getNotification().getBody());

    }
}

private void sendNotificatio(String messageBody) {
    String id="";
    String message="";
    String titles="";

    if (type.equals("json")){
        try {
            JSONObject jsonObject = new JSONObject(messageBody);
            id=jsonObject.getString("id");
            message=jsonObject.getString("message");
            titles= jsonObject.getString("title");

        } catch (JSONException e) {
            e.printStackTrace();
        }

    } else if (type.equals("message")) {
        message= messageBody;
    }
2
  • Y cual es el callback donde se reciben los datos de la push notification?
    – Jorgesys
    el 8 ago. 2017 a las 17:33
  • 1
    lo edite a la pregunta . ..es mi Firebase Message Service
    – Wid Maer
    el 8 ago. 2017 a las 17:45

1 respuesta 1

2

Te comento brevemente sobre la recepción de datos mediante FCM en tu código. Cuando se envía desde el servidor una Push notification, el método onMessageReceived() recibe los datos en formato .json,

  @Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if(remoteMessage.getData().size() >0){
        type="json";
        sendNotificatio(remoteMessage.getData().toString());
    }
    if(remoteMessage.getNotification() !=null) {
        type = "message";
        sendNotificatio(remoteMessage.getNotification().getBody());

    }
}

para posteriormente ser enviados al método sendNotificatio(), es aquí donde se procesa el JSONObject y se obtienen los datos, estas obteniendo id, message y titles, puedes crear un mensaje y llamar un método para asignar el texto a tu TextView, por ejemplo:

private void sendNotificatio(String messageBody) {
    String id="";
    String message="";
    String titles="";

    if (type.equals("json")){
        try {
            JSONObject jsonObject = new JSONObject(messageBody);
            id=jsonObject.getString("id");
            message=jsonObject.getString("message");
            titles= jsonObject.getString("title");

         //*** Metodo para modificar
         setTexto("id: " + id + ", message: " + message + ", titles: " + titles);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    } else if (type.equals("message")) {
        message= messageBody;
    }

El método que realizaría la modificación del texto dentro del TextView sería por ejemplo:

public static void setTexto(String mensaje){
   textView.setText(mensaje);
}

Si deseas enviar el dato entre Actividades puedes usar el bundle para enviar los datos mediante un Intent:

Pasar datos entre activities

4
  • muchas gracias Jorgesys por su respuesta .. logre a capturar el mensaje en un Log .. pero me da error cuando trato de pasar la en una otra actividad... help
    – Wid Maer
    el 9 ago. 2017 a las 13:45
  • lo que quiero hacer , es abrir el mensaje en otra actividad...y siempre me llega null en la otra ctividad
    – Wid Maer
    el 9 ago. 2017 a las 13:46
  • ya lo logre a hacer @Jorgesys... gracias por su ayuda..
    – Wid Maer
    el 9 ago. 2017 a las 14:57
  • @WidMaer revisa mi actualización, si obtuviste los datos y deseas enviar los datos puedes hacerlo mediante un bundle, saludos.
    – Jorgesys
    el 9 ago. 2017 a las 15:12

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.