Я хочу запустить службу обновления местоположения в фоновом режиме. Я хочу добиться того, чтобы запустить службу, когда пользователь получает уведомление от 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 ... on-updates
Фоновая служба Android для обновления местоположения ⇐ Android
Форум для тех, кто программирует под Android
-
Anonymous
1720101843
Anonymous
Я хочу запустить службу обновления местоположения в фоновом режиме. Я хочу добиться того, чтобы запустить службу, когда пользователь получает уведомление от 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)
}
[b][/b]
@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"
}
[b][/b]
Подробнее здесь: [url]https://stackoverflow.com/questions/78706434/android-background-service-for-location-updates[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия