Descripción general
Las notificaciones push de Android son esenciales para impulsar la participación sostenida del usuario y la retención en su aplicación de Android. Le permiten entregar actualizaciones en tiempo real, recordatorios y mensajes personalizados directamente a sus usuarios, mejorando la experiencia general del usuario y la adherencia de su aplicación. OneSignal aprovecha Firebase Cloud Messaging (FCM) pero está diseñado para proporcionar aún más flexibilidad y funcionalidad como se muestra en esta guía.Requisitos
- Dispositivo o emulador Android 7.0+ con “Google Play Store (Services)” instalado.
- Android Studio (las instrucciones de configuración usan Android Studio Meerkat).
- Aplicación y plataforma de OneSignal configuradas.
Configure your OneSignal app and platform
Required setup for push notifications To start sending push notifications with OneSignal, you must first configure your OneSignal app with all the platforms your support—Apple (APNs), Google (FCM), Huawei (HMS), and/or Amazon (ADM).Step-by-step instructions for configuring your OneSignal app.
Step-by-step instructions for configuring your OneSignal app.
Create or select your app
- To add platforms to an existing app, go to Settings > Push & In-App in the OneSignal dashboard.
- To start fresh, click New App/Website and follow the prompts.

Example shows creating a new app.
Set up and activate a platform
- Choose a clear and recognizable name for your app and organization.
- Select the platform(s) you want to configure (iOS, Android, etc.).
- Click Next: Configure Your Platform.

Example setting up your first OneSignal app, org, and channel.
Configure platform credentials
- Android: Set up Firebase Credentials
- iOS: p8 Token (Recommended) or p12 Certificate
- Amazon: Generate API Key
- Huawei: Authorize OneSignal
Choose target SDK

Select which SDK you are using to be navigated to the docs.
Install SDK and save your App ID

Save your App ID and invite additional team members.
Configuración de Android
1. Agregar el SDK de OneSignal
En Android Studio, abra su archivobuild.gradle.kts (Module: app) o build.gradle (Module: app) y agregue OneSignal a sus dependencies.

El ejemplo muestra cómo agregar OneSignal al archivo build.gradle.kts de su aplicación.
Sincronizar Gradle
Después de agregar la dependencia, sincronice su proyecto:- Haga clic en Sync Now en el banner
- O vaya a File > Sync Project with Gradle Files
2. Inicializar el SDK en la clase Application
Es una buena práctica inicializar OneSignal en el métodoonCreate de su clase Application para garantizar la configuración adecuada del SDK en todos los puntos de entrada.
Cómo crear una clase Application
Cómo crear una clase Application
ApplicationClass) y agregue el siguiente código.
Archivo ApplicationClass.kt de ejemplo.
AndroidManifest.xml de su aplicaciónEn su etiqueta <application> agregue android:name=".ApplicationClass" (reemplace .ApplicationClass con el nombre de su clase real si lo estableció en algo diferente).
AndroidManifest.xml con el nombre .ApplicationClass.
ApplicationClass, inicialice OneSignal con los métodos proporcionados.
Reemplace YOUR_APP_ID con su App ID de OneSignal que se encuentra en Settings > Keys & IDs en su panel de OneSignal. Si no tiene acceso a la aplicación de OneSignal, solicite a sus Miembros del equipo que lo inviten.

Archivo ApplicationClass.kt con código de OneSignal agregado.
3. Personalizar íconos predeterminados
Recomendamos configurar sus íconos de notificación para que coincidan con la marca de su aplicación. De lo contrario, OneSignal usará un ícono de campana predeterminado.Probar la integración del SDK de OneSignal
Esta guía le ayuda a verificar que su integración del SDK de OneSignal funciona correctamente al probar las notificaciones push, el registro de suscripción y la mensajería en la aplicación.Verificar suscripciones móviles
Inicie su aplicación en un dispositivo de prueba.
requestPermission durante la inicialización.
Solicitudes de permiso push de iOS y Android
Verifique su panel de OneSignal
- Vaya a Audience > Subscriptions.
- Debería ver una nueva entrada con el estado “Never Subscribed”.

Panel que muestra la suscripción con el estado 'Never Subscribed'
Regrese a la aplicación y toque Permitir en la solicitud.
Actualice la página de Subscriptions del panel de OneSignal.

Panel que muestra la suscripción con el estado 'Subscribed'
Configurar suscripciones de prueba
Las suscripciones de prueba son útiles para probar una notificación push antes de enviar un mensaje.Agregar a Test Subscriptions.

Agregar un dispositivo a Test Subscriptions
Nombre su suscripción.

Panel que muestra el campo 'Name your subscription'
Crear un segmento de usuarios de prueba.
Asigne un nombre al segmento.
Test Users (el nombre es importante porque se usará más adelante).Agregue el filtro Test Users y haga clic en Create Segment.

Crear un segmento 'Test Users' con el filtro Test Users
Enviar push de prueba a través de API
Obtenga su App API Key y App ID.
Actualice el código proporcionado.
YOUR_APP_API_KEY y YOUR_APP_ID en el código a continuación con sus claves reales. Este código utiliza el segmento Test Users que creamos anteriormente.Ejecute el código.
Verifique las imágenes y la entrega confirmada.

Notificación push con imagen en iOS y Android
Verifique la entrega confirmada.

Delivery stats showing confirmed delivery

Confirmed delivery at the device level in Audience Activity
Enviar un mensaje en la aplicación
In-app messages let you communicate with users while they are using your app.Close or background your app on the device.
Create an in-app message.
- In your OneSignal dashboard, navigate to Messages > In-App > New In-App.
- Find and select the Welcome message.
- Set your Audience as the Test Users segment we used previously.

Targeting the 'Test Users' segment with an in-app message
Customize the message content if desired.

Example customization of in-app Welcome message
Set Trigger to 'On app open'.
Schedule frequency.

In-app message scheduling options
Make message live.
Open the app and see the message.

Welcome in-app message shown on devices
- Gathering Subscriptions, setting Test subscriptions, and creating Segments.
- Sending Push with images and Confirmed Delivery using Segments and our Create message API.
- Sending In-app messages.
Identificación del usuario
Anteriormente, demostramos cómo crear Subscriptions móviles. Ahora ampliaremos para identificar Usuarios en todas sus suscripciones (incluidas push, correo electrónico y SMS) usando el SDK de OneSignal. Cubriremos External IDs, etiquetas, suscripciones multicanal, privacidad y seguimiento de eventos para ayudarlo a unificar e involucrar usuarios en todas las plataformas.Asignar External ID
Use un External ID para identificar usuarios de manera consistente en dispositivos, direcciones de correo electrónico y números de teléfono usando el identificador de usuario de su backend. Esto garantiza que su mensajería permanezca unificada en todos los canales y sistemas de terceros (especialmente importante para Integraciones). Establezca el External ID con el métodologin de nuestro SDK cada vez que sean identificados por su aplicación.
Agregar etiquetas de datos
Las Etiquetas son pares clave-valor de datos de cadena que puede usar para almacenar propiedades de usuario (comousername, role o preferencias) y eventos (como purchase_date, game_level o interacciones de usuario). Las etiquetas impulsan la Personalización de mensajes avanzada y la Segmentación permitiendo casos de uso más avanzados.
Establezca etiquetas con los métodos addTag y addTags de nuestro SDK a medida que ocurren eventos en su aplicación.
En este ejemplo, el usuario alcanzó el nivel 6 identificable por la etiqueta llamada current_level establecida en un valor de 6.

A user profile in OneSignal with a tag called "current_level" set to "6"

Segment editor showing a segment targeting users with a current_level value of greater than 4 and less than 10

Screenshot showing a push notification targeting the Level 5-10 segment with a personalized message

The push notification is received on an iOS and Android device with the personalized content
Agregar suscripciones de correo electrónico y/o SMS
Earlier we saw how our SDK creates mobile subscriptions to send push and in-app messages. You can also reach users through emails and SMS channels by creating the corresponding subscriptions.- Use the
addEmailmethod to create email subscriptions. - Use the
addSmsmethod to create SMS subscriptions.

A user profile with push, email, and SMS subscriptions unified by External ID
- Obtain explicit consent before adding email or SMS subscriptions.
- Explain the benefits of each communication channel to users.
- Provide channel preferences so users can select which channels they prefer.
Privacidad y consentimiento del usuario
To control when OneSignal collects user data, use the SDK’s consent gating methods:setConsentRequired(true): Prevents data collection until consent is given.setConsentGiven(true): Enables data collection once consent is granted.
Solicitar permisos de push
Instead of callingrequestPermission() immediately on app open, take a more strategic approach. Use an in-app message to explain the value of push notifications before requesting permission.
For best practices and implementation details, see our Prompt for push permissions guide.
Escuchar eventos de push, usuario y en la aplicación
Use SDK listeners to react to user actions and state changes. The SDK provides several event listeners for you to hook into. See our SDK reference guide for more details.Eventos de notificación push
addClickListener(): Detect when a notification is tapped. Helpful for Deep Linking.addForegroundLifecycleListener(): Control how notifications behave in foreground.
Cambios de estado del usuario
addObserver()for user state: Detect when the External ID is set.addPermissionObserver(): Track the user’s specific interaction with the native push permission prompt.addObserver()for push subscription: Track when the push subscription status changes.
Eventos de mensajes en la aplicación
addClickListener(): Handle in-app click actions. Ideal for deep linking or tracking events.addLifecycleListener(): Track full lifecycle of in-app messages (shown, clicked, dismissed, etc.).
Configuración avanzada y capacidades
Explore more capabilities to enhance your integration:- 🔁 Migrating to OneSignal from another service
- 🌍 Location tracking
- 🔗 Deep Linking
- 🔌 Integrations
- 🧩 Mobile Service Extensions
- 🛎️ Action buttons
- 🌐 Multi-language messaging
- 🛡️ Identity Verification
- 📊 Custom Outcomes
- 📲 Live Activities
Configuración y referencia del SDK móvil
Make sure you’ve enabled all key features by reviewing the Mobile push setup guide. For full details on available methods and configuration options, visit the Mobile SDK reference.Diseño de notificación personalizado
Android 12 and higher enforce system templates for custom notifications. However, you can still customize your layout using Android’s standard notification styles.- Follow Android’s custom notification guide
- Apply changes via the Notification Service Extension
Deshabilitar el comportamiento de apertura predeterminado
When a notification is clicked, OneSignal will resume your app, or open your launcher Activity if your app was swiped away. To prevent OneSignal from auto-opening your launcher Activity when a notification is clicked, add this to yourAndroidManifest.xml:
onCreate method in your Application class. You will need to call startActivity from this callback to take the user to your intended Activity.
Datos en segundo plano y anulaciones de push
- Use the Notification Service Extension to handle background data or override notification visuals
- Use the SDK Notification Event Handlers to read additional data from a notification
Soporte de idiomas de derecha a izquierda (RTL)
To support RTL languages in notifications and UI, add this to yourAndroidManifest.xml:
support@onesignal.comPlease include:- Details of the issue you’re experiencing and steps to reproduce if available
- Your OneSignal App ID
- The External ID or Subscription ID if applicable
- The URL to the message you tested in the OneSignal Dashboard if applicable
- Any relevant logs or error messages