Я хочу запустить службу обновления местоположения в фоновом режиме. Я хочу добиться того, чтобы запустить службу, когда пользователь получает уведомление от Firebase FCM в onMessageReceived(remoteMessage: RemoteMessage), когда приложение находится в режиме forground onMessageReceived запускает службу, но когда приложение закрывается или не находится на переднем плане, местоположение не обновляется или служба не запускается в фоновом режиме. Каков правильный подход к получению местоположения пользователя в фоновом режиме, когда приложение находится в фоновом режиме или в выключенном состоянии
@AndroidEntryPoint
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
if (remoteMessage.data.isNotEmpty()) {
Log.d("FirebaseLogs", "Remote message data: ${remoteMessage.data}")
Intent(this, LocationBackgroundService::class.java).also { intent ->
intent.action = LocationBackgroundService.ACTION_START
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent)
} else {
startService(intent)
}
}
} else {
Log.d("FirebaseLogs", "Remote message data is empty")
}
override fun onNewToken(token: String) {
super.onNewToken(token)
SharedPrefDataStore.init().setValue(this, FCM_TOKEN, token)
}
@AndroidEntryPoint
class LocationBackgroundService : Service() {
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private lateinit var locationClient: LocationClient
private lateinit var db: FirebaseFirestore
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
db = FirebaseFirestore.getInstance()
locationClient = DefaultLocationClient(
applicationContext,
LocationServices.getFusedLocationProviderClient(applicationContext)
)
createNotificationChannel()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when(intent?.action){
ACTION_START -> start()
ACTION_STOP -> stop()
}
//return START_STICKY
return super.onStartCommand(intent, flags, startId)
}
private fun start() {
val pendingIntent: PendingIntent =
Intent(this, MainActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity(
this, 0, notificationIntent,
PendingIntent.FLAG_IMMUTABLE
)
}
val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentTitle("Tracking location...")
.setContentText("")
.setSmallIcon(R.drawable.we_care_small)
.setOngoing(true)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
locationClient
.getLocationUpdates(10000L)
.catch { e -> e.printStackTrace() }
.onEach { location ->
val lat = location.latitude.toString()
val long = location.longitude.toString()
val geoPoint = GeoPoint(location.latitude, location.longitude)
saveUserLocation(geoPoint)
val updatedNotification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentTitle("Tracking location...")
.setContentText("Location: ($lat, $long)")
.setSmallIcon(R.drawable.we_care_small)
.setContentIntent(pendingIntent)
.setOngoing(true)
.build()
notificationManager.notify(1, updatedNotification)
}
.launchIn(serviceScope)
startForeground(1, notification.build())
}
private fun createNotificationChannel() {
val channel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = "Channel for location service"
}
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(channel)
}
private fun stop() {
stopForeground(true)
stopSelf()
}
override fun onDestroy() {
super.onDestroy()
serviceScope.cancel()
}
private fun saveUserLocation(geoPoint: GeoPoint) {
db.collection(USER_LOCATION)
.document(Firebase.auth.currentUser?.uid.toString())
.update("geo_location", geoPoint)
.addOnCompleteListener {
Log.d(TAG, "Save UserLocation from Service :: " + it.isSuccessful)
}
.addOnFailureListener {
Log.d(TAG, "Fail to save UserLocation :: " + it.message)
}
}
companion object {
const val ACTION_START = "ACTION_START"
const val ACTION_STOP = "ACTION_STOP"
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... background
Firebase FCM не активируется, когда приложение находится в фоновом режиме. Я хочу запустить фоновую службу для обновлени ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как реализовать фоновую службу живого отслеживания с помощью Firebase во Flutter?
Anonymous » » в форуме Android - 0 Ответы
- 18 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Firebase onMessageReceived не вызывается, когда приложение находится в фоновом режиме
Anonymous » » в форуме Android - 0 Ответы
- 22 Просмотры
-
Последнее сообщение Anonymous
-