Documente Academic
Documente Profesional
Documente Cultură
NOTIFICACIONES EN ANDROID
FIREBASE CLOUD MESSAGING (FCM)
INTEGRANTES:
implementation 'com.google.firebase:firebase-messaging:17.3.4'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
El primer paso sería conectarnos a Firebase.
public MyFirebaseInstanceIdService() {
}
@Override
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Token: " + token);
FirebaseMessaging.getInstance().subscribeToTopic(TOPIC_GLOBAL);
enviarTokenAlServidor(token);
}
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".MyFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INTANCE_ID_EVENT" />
</intent-filter>
</service>
Google-services.json
Main Activity
FirebaseMessaging.getInstance().subscribeToTopic("news")
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
String msg = "msg_subscribed";
if (!task.isSuccessful()) {
msg = "msg_subscribe_failed";
}
Log.d(LOGTAG, msg);
}
});
}
}
Layout
colors.xml
<color name="lightgray">#ededed</color>
<color name="window_background">#EEEEEE</color>
<color name="Turquoise">#3EC1C2</color>
cerclebackground.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >
<EditText
android:id="@+id/txt_NombreUsuario"
android:hint="Nombre grupo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background_normal"/>
</LinearLayout>
<RelativeLayout card_view_mensajes.xml
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5sp"
android:paddingRight="5sp">
<android.support.v7.widget.CardView
android:id="@+id/cvMensaje"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="@android:color/transparent"
card_view:cardElevation="0dp">
<LinearLayout
android:id="@+id/mensajeBG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/out_message_bg"
android:orientation="vertical">
<TextView
android:id="@+id/msEmisor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="240sp"
android:text="Jary Rodriguez"
android:textColor="@android:color/holo_green_dark"
android:textStyle="bold" />
<TextView
android:id="@+id/msTexto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="240sp"
android:text="hola amigos como estan" />
<TextView
android:id="@+id/msHora"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="12:00 pm"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#0277BD" />
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
activity_enviar_notificacion.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/eTEsribirMensaje"
android:layout_width="323dp"
android:layout_height="61dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginEnd="3dp"
android:layout_marginRight="3dp"
android:layout_toStartOf="@+id/bTenviarMensaje"
android:layout_toLeftOf="@+id/bTenviarMensaje"
android:hint="Escribe un mensaje..." />
<Button
android:id="@+id/bTenviarMensaje"
android:layout_width="99dp"
android:layout_height="58dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:hint="Enviar" />
<android.support.v7.widget.RecyclerView
android:id="@+id/rvMensajes"
android:layout_width="match_parent"
android:layout_height="660dp"
android:layout_above="@+id/eTEsribirMensaje"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="13dp"
tools:listitem="@layout/card_view_mensajes"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
</LinearLayout>
class MensajeDeTexto
public MensajeDeTexto() {}
public String getId() {return id; }
public void setId(String id) {this.id = id; }
public String getMensaje() {return mensaje; }
public void setMensaje(String mensaje) { this.mensaje = mensaje;}
public String getEmsior() { return emisor; }
public void setEmisor(String emisor) { this.emisor = emisor; }
public int getTipoMensaje() { return tipoMensaje; }
public void setTipoMensaje(int tipoMensaje) { this.tipoMensaje = tipoMensaje;}
public String getHoraDelMensaje() { return HoraDelMensaje; }
public void setHoraDelMensaje(String horaDelMensaje) { HoraDelMensaje = horaDelMensaje;}
}
class FCM
{
"to": "/topics/news",
"notification": {
"title": "Noticia desde el servidor 1",
"body": "Descripción de la noticia desde el servidor "
},
"data": {
"titulo": "Este es el titular",
"mensaje": "Aquí estará todo el contenido de la noticia",
"emisor": "Randy Rodriguez",
"hora": "09:12:22",
"token_emisor": "dfdf"
}
}
Nota: Ir a documento
class MensajeriaAdapter
if(mensajeDeTextos.get(position).getTipoMensaje()==1){//EMISOR
holder.mensajeBG.setBackgroundResource(R.drawable.in_message_bg);
rl.addRule(RelativeLayout.ALIGN_PARENT_LEFT,0);
rl.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
llEmisor.gravity = Gravity.RIGHT;
llMensaje.gravity = Gravity.RIGHT;
llHora.gravity = Gravity.RIGHT;
fl.gravity = Gravity.RIGHT;
holder.TvMensaje.setGravity(Gravity.RIGHT);
}else
if(mensajeDeTextos.get(position).getTipoMensaje()==2){//RECEPTOR
holder.mensajeBG.setBackgroundResource(R.drawable.out_message_bg);
rl.addRule(0,RelativeLayout.ALIGN_PARENT_RIGHT);
rl.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
llEmisor.gravity = Gravity.LEFT;
llMensaje.gravity = Gravity.LEFT;
llHora.gravity = Gravity.LEFT;
fl.gravity = Gravity.LEFT;
holder.TvMensaje.setGravity(Gravity.LEFT);
}
Nota: Ir a documento
class ActivityEnviarNotificacion
public class ActivityEnviarNotificacion extends AppCompatActivity {
public static final String MENSAJE = "MENSAJE";
private RecyclerView rv;
private Button bTEnviarMensaje;
private EditText eTEscribirMensaje;
private List<MensajeDeTexto> mensajeDeTextos;
private MensajeriaAdapter adapter;
private BroadcastReceiver bR;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enviar_notificacion);
mensajeDeTextos = new ArrayList<>();
bTEnviarMensaje = (Button) findViewById(R.id.bTenviarMensaje);
eTEscribirMensaje = (EditText) findViewById(R.id.eTEsribirMensaje);
rv = (RecyclerView) findViewById(R.id.rvMensajes);
LinearLayoutManager lm = new LinearLayoutManager(this);
rv.setLayoutManager(lm);
adapter = new MensajeriaAdapter(mensajeDeTextos,this);
rv.setAdapter(adapter);
bTEnviarMensaje.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String mensaje = eTEscribirMensaje.getText().toString().trim();
if(!mensaje.isEmpty()){
Date date = new Date();
DateFormat hourdateFormat = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
FCM.send_FCM_Notification("/topics/news",
FirebaseInstanceId.getInstance().getToken(),"AIzaSyA6FKBoW_GHhOuyLy7UmtbeA-ij9kWmmP4",mensaje);
CreateMensaje(mensaje,hourdateFormat.format(date),MainActivity.usuario,1);
eTEscribirMensaje.setText("");
}
}
});
eTEscribirMensaje.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
rv.postDelayed(new Runnable() {
@Override
public void run() {
if(((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).isActive()){
setScrollbarChat();
}else{
rv.postDelayed(this,100);
}
}
},100);
}
});
setScrollbarChat();
bR = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String mensaje = intent.getStringExtra("key_mensaje");
String hora = intent.getStringExtra("key_hora");
String emisorname = intent.getStringExtra("key_emisor");
CreateMensaje(mensaje,hora,emisorname,2);
adapter.notifyDataSetChanged();
setScrollbarChat();
}
};
}
public void CreateMensaje(String mensaje,String hora,String emisor,int tipoDeMensaje){
MensajeDeTexto mensajeDeTextoAuxiliar = new MensajeDeTexto();
mensajeDeTextoAuxiliar.setId("0");
mensajeDeTextoAuxiliar.setMensaje(mensaje);
mensajeDeTextoAuxiliar.setEmisor(emisor);
mensajeDeTextoAuxiliar.setTipoMensaje(tipoDeMensaje);
mensajeDeTextoAuxiliar.setHoraDelMensaje(hora);
mensajeDeTextos.add(mensajeDeTextoAuxiliar);
}
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(bR);
}
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(bR,new IntentFilter(MENSAJE));
}
https://install.advancedrestclient.com/install
https://fcm.googleapis.com/fcm/send
Content-Type: application/json
Authorization: key=AIzaSyA6FKBoW_GHhOuyLy7UmtbeA-ij9kWmmP4
{
"to":
"AAAABs66tKY:APA91bH7YRAF443_k34FtDzyr1slehN9YGZRFWmV_ywNCLKUTW7puEuCUv9oVmxXmlQneb_XT
zwGP2Q8GxSS3xyHoGNs43oJ_f7wDYuiRjPX-fDo4QCYs96tmnULnNZARSYe2IxK2GCA",
"notification": {
"title": "Noticia desde el servidor 1",
"body": "Descripción de la noticia desde el servidor "
},
"data": {
"titulo": "Este es el titular",
"descripción": "Aquí estará todo el contenido de la noticia"
}
}