--- title: "Gerenciando notificações push em primeiro plano" slug: "mobile-foreground-notifications-handling" updated: 2026-06-12T10:30:51Z published: 2026-06-12T10:30:51Z canonical: "docs.xtremepush.com/mobile-foreground-notifications-handling" --- > ## Documentation Index > Fetch the complete documentation index at: https://docs.xtremepush.com/llms.txt > Use this file to discover all available pages before exploring further. # Gerenciando notificações push em primeiro plano Controle o que acontece quando uma notificação push móvel é recebida em primeiro plano É importante definir o comportamento correto para a situação quando uma notificação push é recebida em primeiro plano. Você não quer interromper o fluxo de trabalho do usuário, mas ainda assim entregar informações importantes ao usuário. Normalmente, você tem 3 opções para lidar com uma notificação push recebida em primeiro plano: - Mostrar a notificação no estilo do sistema operacional - Mostrar um diálogo personalizado - Ignore a notificação O comportamento padrão no iOS é ignorar as notificações. O comportamento padrão no Android é mostrar a notificação no estilo do sistema operacional. Você pode encontrar informações sobre como mudar isso abaixo. ## iOS O comportamento padrão no iOS é não mostrar notificações em primeiro plano com alerta, som e distintivo. Se quiser mostrar notificações em primeiro plano, pode fazer o seguinte: **Swift** ```swift XPush.registerForegroundNotificationOptions { (message: XPMessageResponse) in        return [.alert, .badge, .sound] } ``` **Objective-C** ```objectivec [XPush registerForegroundNotificationOptions:^XPNotificationType(XPMessage *message) {    return XPNotificationType_Alert | XPNotificationType_Sound | XPNotificationType_Badge; }]; ``` Se você tem diferentes tipos de mensagens no seu app, talvez queira implementar um comportamento diferente para cada uma. Isso pode ser alcançado usando a seguinte lógica dentro da função: **Swift** ```swift XPush.registerForegroundNotificationOptions { (message: XPMessageResponse) in    if x.message.data?["showMessage"] != nil {        return [.alert, .sound, .badge]    }    return [] } ``` **Objective-C** ```objectivec [XPush registerForegroundNotificationOptions:^XPNotificationType(XPMessage *message) {    If (message.data[@"type"] == @"article") {        return XPNotificationType_Alert | XPNotificationType_Sound | XPNotificationType_Badge;    }    return XPNotificationType_None; }]; ``` O método descrito acima (`registerForegroundNotificationOptions`) foi projetado para definir o comportamento das notificações padrão do iOS. Para implementar o comportamento personalizado (como diálogos personalizados), você deve usar outro método chamado message response handler: **Swift** ```swift XPush.registerMessageResponseHandler { (response: XPMessageResponse) in    if response.action.type == .present {        // Logic when message received in foreground    } } ``` **Objective-C** ```objectivec [XPush registerMessageResponseHandler:^(XPMessageResponse *response) {    if (response.action.type == XPActionType_Present) {        // Logic when message received in foreground    } }]; ``` Após mostrar um diálogo personalizado, você pode prosseguir programaticamente com a ação de clique da mensagem (por exemplo, abrir URL) quando o usuário clica em um botão: **Swift** ```swift XPush.click(response.message) ``` **Objective-C** ```objectivec [XPush clickMessage:response.message actionIdentifier:nil]]; ``` Você também pode rastrear a mensagem como clicada sem executar nenhuma ação (por exemplo, abrir URL): **Swift** ```swift XPush.reportMessageClicked(response.message) ``` **Objective-C** ```objectivec [XPush reportMessageClick:response.message actionIdentifier:nil]]; ``` Encontre um exemplo completo abaixo: **Swift** ```swift // Show OS notifications in foreground XPush.registerForegroundNotificationOptions { (message :XPMessageResponse) in    return [.alert, .sound, .badge] } // Register custom message handler XPush.registerMessageResponseHandler { (response: XPMessageResponse) in        if response.action.type == .present {            // Show an article dialog with "View" button            self.showArticleDialog(response.message, clickCallback: {               XPush.clickMessage(response.message)            })        } } ``` **Objective-C** ```objectivec // Show OS notifications in foreground [XPush registerForegroundNotificationOptions: ^XPNotificationType(XPMessageResponse *response) {        return XPNotificationType_Alert | XPNotificationType_Sound | XPNotificationType_Badge; }]; // Register custom message handler [XPush registerMessageResponseHandler: ^(XPMessageResponse * _Nonnull response) {                if (response.action.type == XPActionType_Present) {            // Show an article dialog with "View" button            [self showArticleDialog: response.message viewButtonCallback: ^{                // Process message click                [XPush clickMessage:response.message actionIdentifier:nil];            }];        }    }]; ``` ## Android No Android, ao inicializar `PushConnector`, você pode definir o comportamento para notificações em primeiro plano definindo `.setShowForegroundNotifications()` para ou `true` `false` (o valor padrão é `true`). Se configurado para `false`, as notificações não aparecerão enquanto seu app estiver em primeiro plano, a menos que você chame `mPushConnector.showNotification()`especificamente . ```java new PushConnector.Builder(XPUSH_APP_KEY, GOOGLE_PROJECT_NUMBER)        .setShowForegroundNotifications(false)        .create(this); ``` Agora, quando uma mensagem é recebida, você pode escolher como quer lidar com ela. Para isso, você usará o `messageResponseReceived` callback ( [veja aqui](/documentation/docs/pt-br/mobile-message-custom-handling) para mais detalhes). ```java @Override public void messageResponseReceived(Message messagePayload,                                    HashMap responsePayload,                                    WeakReference uiReference) {    if (responsePayload.get("responseType").equals("present")) {            } } ``` Algumas das funções úteis que você pode usar são: 1. `showNotification()`. Para mostrar a notificação push: ```java mPushConnector.showNotification(messagePayload); ``` 2. `clickMessage()`. Os parâmetros são a mensagem e a ação dessa mensagem para clicar. Se configurado como nulo, a ação padrão da notificação será usada. Então, se a mensagem tiver a ação de clique *Abrir URL*, *a URL será aberta no navegador do telefone. ```java mPushConnector.clickMessage(messagePayload, null); ``` 3. `reportMessageClicked`. Os parâmetros são a mensagem a reportar como clicado e a ação a reportar como clicada (deve ser nula se não estiver usando notificações interativas). ```java mPushConnector.reportMessageClicked(messagePayload, null); ``` 4. `reportMessageDismissed`. Os parâmetros são a mensagem a reportar como fechada e a ação a reportar como fechada (deve ser nula se não estiver usando notificações interativas) ```java mPushConnector.reportMessageDismissed(messagePayload, null); ```