studio notificaciones enviar ejemplo app android firebase google-cloud-messaging firebase-cloud-messaging

enviar - notificaciones push android php mysql



Notificación de mensajes en la nube de Firebase no recibida por el dispositivo (17)

Como si quisiera que su aplicación también se ejecute en> 24 versiones, siga estos:

1.Agregue esto en sus strings.xml

<string name = "default_notification_channel_id" translatable = "false"> fcm_default_channel

  1. Agregue estos metadatos en su archivo de manifiesto:

<metadatos android: name = "com.google.firebase.messaging.default_notification_channel_id" android: value = "@ string / default_notification_channel_id" />

3.para crear notificaciones (con imágenes) use este método donde maneja las notificaciones, si directamente agrega el servicio firebasemessaging o si está usando alguna clase de utilidad, agregue esa clase de utilidad:

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) public static void createBigNotification(Bitmap bitmap, int icon, String message, Uri alarmSound) { final int NOTIFY_ID = 0; // ID of notification NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE); String id = mContext.getString(R.string.default_notification_channel_id); // default_channel_id String title = mContext.getString(R.string.app_name); Intent intent; NotificationCompat.Builder builder; if (notificationManager == null) { notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); } PendingIntent resultPendingIntent; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel mChannel = notificationManager.getNotificationChannel(id); if (mChannel == null) { mChannel = new NotificationChannel(id, title, importance); mChannel.enableVibration(true); mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); notificationManager.createNotificationChannel(mChannel); } builder = new NotificationCompat.Builder(mContext, id); intent = new Intent(mContext, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); resultPendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0); NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(); bigPictureStyle.setBigContentTitle(title); bigPictureStyle.setSummaryText(Html.fromHtml(message).toString()); bigPictureStyle.bigPicture(bitmap); builder.setContentTitle(title) // required .setSmallIcon(R.drawable.app_icon) // required .setContentText(message) // required .setDefaults(Notification.DEFAULT_ALL) .setAutoCancel(true) .setSound(alarmSound) .setStyle(bigPictureStyle) .setContentIntent(resultPendingIntent) .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon)) .setTicker(title) .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); } else { builder = new NotificationCompat.Builder(mContext, id); intent = new Intent(mContext, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); resultPendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0); NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(); bigPictureStyle.setBigContentTitle(title); bigPictureStyle.setSummaryText(Html.fromHtml(message).toString()); bigPictureStyle.bigPicture(bitmap); builder.setContentTitle(title) // required .setSmallIcon(R.drawable.app_icon) // required .setContentText(message) // required .setDefaults(Notification.DEFAULT_ALL) .setAutoCancel(true) .setSound(alarmSound) .setStyle(bigPictureStyle) .setContentIntent(resultPendingIntent) .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon)) .setTicker(title) .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}) .setPriority(Notification.PRIORITY_HIGH); } Notification notification = builder.build(); notificationManager.notify(NOTIFY_ID, notification); }

Siga estos pasos y su notificación llegará en la bandeja de notificaciones.

Tengo un problema con FireBase Cloud Messaging en el que obtengo el token del dispositivo y envío la prueba de notificación a través de la consola de notificaciones de Google Firebase, sin embargo, la notificación nunca se registra ni se envía al dispositivo virtual Android. La documentación para FCM es casi exactamente el código que tengo a continuación y poco más sobre lo que tendría que hacer para que las notificaciones push funcionen con firebase. He revisado toda la información de configuración (adiciones de build.gradle, Instalación de servicios de google play, etc.) como se especifica en la documentación, pero aún no tengo mensajes generados. Recibo un error único inmediatamente después de enviar la notificación que dice "I / FA: no se encuentra el Administrador de etiquetas y, por lo tanto, no se usará", pero esa es la única información que se emite y no encontré nada relacionado con la etiqueta Requisitos del gerente y FCM en los googles. ¿Qué tiene de malo el código de que no recibo mis notificaciones push al logcat o al dispositivo? Por favor, hágame saber cualquier información adicional que pueda ser útil. Gracias.

NotificationGenie.java

public class NotificationGenie extends FirebaseMessagingService { private static final String TAG = "Firebase_MSG"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { // TODO(developer): Handle FCM messages here. // If the application is in the foreground handle both data and notification messages here. // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. sendNotification(remoteMessage.getNotification().getBody()); Log.d(TAG, "From: " + remoteMessage.getFrom()); Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody()); } private void sendNotification(String messageBody) { Intent intent = new Intent(this, PostLoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.tf2spyprofile) .setContentTitle("FCM Message") .setContentText(messageBody) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); } }

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.test.movile_android"> <!-- To auto-complete the email text field in the login form with the user''s emails --> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.READ_PROFILE" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".LoginActivity" android:label="@string/title_activity_login"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".DashBoardActivity" android:label="@string/title_activity_dash_board" android:theme="@style/AppTheme.NoActionBar"> </activity> <activity android:name=".NewOrderActivity" android:label="@string/title_activity_dash_board" android:theme="@style/AppTheme.NoActionBar"> </activity> <activity android:name=".PostLoginActivity" android:label="@string/title_activity_dash_board" android:theme="@style/AppTheme.NoActionBar"> </activity> </application> <service android:name=".NotificationGenie"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service>


Cuando copie el token de su dispositivo, podría copiar el espacio, verifique que haya copiado el token correcto


Debe seguir el siguiente código de manifiesto (debe tener el servicio en manifiesto)

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="soapusingretrofitvolley.firebase"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <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.INSTANCE_ID_EVENT"/> </intent-filter> </service> </application> </manifest>


En mi caso, noté que al manifiesto combinado le faltaba el receptor. Entonces tuve que incluir:

<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> </intent-filter> </receiver>


Ha colocado su servicio fuera de la etiqueta de la aplicación. Cambiar de fondo a esto.

<service android:name=".NotificationGenie"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> </application>


He estado trabajando en toda esta publicación y en otras, así como en videos tutoriales sin poder resolver mi problema de no recibir mensajes, sin embargo, el token de registro funcionó.

Hasta entonces solo había estado probando la aplicación en el emulador. Después de probarlo en un teléfono físico, funcionó instantáneamente sin ningún cambio previo en el proyecto.


Llame a super.OnMessageReceived() en el método Overriden. ¡Esto funcionó para mí! ¡Finalmente!


Me enfrenté al mismo problema de los mensajes en la nube de Firebase que no recibió el dispositivo.

En mi caso, el nombre del paquete definido en Firebase Console Project fue diferente al que se definió en Manifest & Gradle de mi Android Project.

Como resultado, recibí el token correctamente pero no recibí ningún mensaje.

Para resumir, es obligatorio que el nombre del paquete de la consola Firebase y las coincidencias de Manifiesto y Gradle.

También debe tener en cuenta que para recibir mensajes enviados desde Firebase Console, la aplicación debe estar en segundo plano, no iniciarse ni ocultarse.


Me enfrenté al mismo problema, pero todavía tenía algunos restos en mi manifiesto del antiguo GCM. Cuando saqué el siguiente permiso de mi manifiesto, solucionó el error. com.google.android.c2dm.permission.RECEIVE


Si acaba de agregar FCM a una aplicación existente, NO se llamará a onTokenRefresh() . Lo ejecuté desinstalando la aplicación e instalándola nuevamente.


Tuve el mismo problema y se resuelve definiendo habilitado, exportado a verdadero en mi servicio

<service android:name=".MyFirebaseMessagingService" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service>


Tuve este problema, revisé mi código. Traté de arreglar todo lo que se mencionó aquí. Por último, el problema era tan estúpido. La Sync mi dispositivo estaba desactivada. esa fue la única razón por la que no recibí las notificaciones como se esperaba.


Tuve un problema similar, pero en mi caso me faltaba el complemento de google-services de mi compilación Gradle (estaba agregando Firebase a un proyecto existente).

build.gradle siguiente a mi root build.gradle :

classpath ''com.google.gms:google-services:3.1.0''

y lo siguiente al final de mi app build.gradle :

apply plugin: ''com.google.gms.google-services''

Luego tuve que descargar el archivo google-services.json de Firebase Console (que originalmente importó un proyecto existente de Google Cloud) y copiarlo en mi directorio de app .


tal vez sea por la conexión, cambié la conexión de Ethernet a inalámbrica, funcionó sin hacer nada más


"También debe tener en cuenta que para recibir mensajes enviados desde Firebase Console, la aplicación debe estar en segundo plano, no iniciada ni oculta". --- Según el comentario de @Laurent Russier.

Nunca recibí ningún mensaje de Firebase, hasta que puse mi aplicación en segundo plano.

Esto es cierto solo en la conexión usb para el emulador, también recibe notificaciones en primer plano


private void sendNotification(String message) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); int requestCode = 0; PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT); Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.URI_COLUMN_INDEX); NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentText(message) .setColor(getResources().getColor(R.color.colorPrimaryDark)) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("FCM Message") .setContentText("hello").setLargeIcon(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap()) .setStyle(new NotificationCompat.BigPictureStyle() .bigPicture(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap())) .setAutoCancel(true) .setSound(sound) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, noBuilder.build());


<activity android:name=".activity.MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- Firebase Notifications --> <service android:name=".service.MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> <service android:name=".service.MyFirebaseInstanceIDService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> </intent-filter> </service>