Serviço em primeiro plano
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.
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:
- 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.
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)
}
}
}
- Em seguida, inicie o serviço em primeiro plano antes de lançar o deep link.
- Então, lance o deep link usando um intent para iniciar o outro aplicativo através do seu 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:
<service
android:name=".MyForegroundService"
android:exported="false"
android:foregroundServiceType="dataSync" />Updated 5 months ago
Did this page help you?