---
updatedAt: 2026-04-23T15:06:05.000Z
agentTools:
  siteIndex: https://docs.cielo.com.br/llms.txt
  projectIndex: https://docs.cielo.com.br/cielo-smart/llms.txt
---

# Serviço em primeiro plano

<Callout icon="👍" theme="okay">
  Um serviço em primeiro plano é um tipo de serviço Android que continua executando tarefas mesmo quando o aplicativo não está visível na tela. A principal diferença entre um serviço comum e um serviço em primeiro plano é que o segundo exibe uma notificação persistente, informando ao usuário que está ativo.
</Callout>

Para executar tarefas críticas em segundo plano utilizando um serviço em primeiro plano e, em seguida, iniciar uma comunicação via deep link com outro aplicativo, siga estes passos:

1. Primeiro, crie um serviço em primeiro plano. Ou seja, implemente um serviço que seja executado em primeiro plano com uma notificação persistente.

```Text Exemplo de implementação do serviço em primeiro plano
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat

class MyForegroundService : Service() {
  companion object {
    const val CHANNEL_ID = "ForegroundServiceChannel"
}

override fun onCreate() {
   super.onCreate()
   createNotificationChannel()
   val notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
     .setContentTitle("Foreground Service")
     .setContentText("Performing critical tasks in the background")
     .setSmallIcon(android.R.drawable.ic_dialog_info)
      .build()
   startForeground(1, notification)
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    // Perform critical background tasks here
   return START_NOT_STICKY
}

override fun onDestroy() {
  super.onDestroy()
  stopForeground(true)
}

override fun onBind(intent: Intent?): IBinder? = null

private fun createNotificationChannel() {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      val serviceChannel = NotificationChannel(
        CHANNEL_ID,
        "Foreground Service Channel",
        NotificationManager.IMPORTANCE_DEFAULT
      )
      val manager = getSystemService(NotificationManager::class.java)
      manager?.createNotificationChannel(serviceChannel)
      }
  }
}

```

2. Em seguida, inicie o serviço em primeiro plano antes de lançar o deep link.
3. Então, lance o deep link usando um intent para iniciar o outro aplicativo através do seu deep link.

```Text Exemplo de como iniciar o serviço em primeiro plano e lançar o deep link
import android.content.Context
import android.content.Intent
import android.net.Uri

fun startForegroundServiceAndLaunchDeepLink(context: Context, deepLink: String) {
  // Start the foreground service
val serviceIntent = Intent(context, MyForegroundService::class.java)
context.startService(serviceIntent)

// Launch the other app using its deep link
try {
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(deepLink))
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    context.startActivity(intent)
} catch (e: Exception) {
    e.printStackTrace()
    // Handle the case where the deep link or app is not available
  }
}
```

# Observações

* Substitua Foreground Service e Performing critical tasks in the background por textos apropriados para o seu aplicativo.
* Certifique-se de que o serviço em primeiro plano seja encerrado quando não for mais necessário para evitar o uso desnecessário de recursos.

Adicione o serviço ao seu AndroidManifest.xml:

```xml AndroidManifest.xml
<service
  android:name=".MyForegroundService"
  android:exported="false"
  android:foregroundServiceType="dataSync" />
```

<br />