`Мне нужна такая функциональность, как мое приложение, которое будет получать данные из API и обновлять данные в базе данных каждые 15-16 минут, поэтому я использую для этого периодическую задачу диспетчера работ. Но диспетчер работ работает только тогда, когда приложение находится в фоновом режиме (список последних приложений), и если я проведу пальцем вверх от списка последних приложений (фон), то менеджер работ больше не работает, и когда я запускаю свое приложение снова, тогда работает только оно. У меня аппарат самсунг ф62. Я также пытаюсь выполнить автоматический запуск в соответствии с настройками, но функция автоматического запуска не является их функцией, а оптимизация батареи не ограничена, что также не работает.
Рабочий класс -:
@HiltWorker
class NewsWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted params: WorkerParameters,
) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
val newsRepository = ServiceLocator.newsRepository
Log.d("worker call", "this is a worker call")
var result: Result? = null
try {
newsRepository.workManagerRequest()
.catch {
result = Result.failure()
Log.d("worker call", "this is a worker call failure from 1st catch")
}
.collect { flowResult ->
when (flowResult) {
is Results.Success -> {
Log.d("worker call", "this is a worker call Success")
// Handle the successful case
// You can process the PagingData here
showNotification()
}
is Results.Error -> {
Log.d("worker call", "this is a worker call failure from Result.Error")
// Handle the error case
result = Result.failure()
}
}
if (result != null) return@collect
}
} catch (e: Exception) {
Log.d("worker call", "this is a worker call failure from second catch :$e")
result = Result.failure()
}
return result ?: Result.success()
}
private fun showNotification() {
val notificationManager = NotificationManagerCompat.from(applicationContext)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (ContextCompat.checkSelfPermission(
applicationContext,
Manifest.permission.ACCESS_NOTIFICATION_POLICY
) == PackageManager.PERMISSION_GRANTED
) {
// Permission is granted, proceed with creating the channel
val channel = NotificationChannel(
"News Channel ID",
"News Channel",
NotificationManager.IMPORTANCE_DEFAULT
)
notificationManager.createNotificationChannel(channel)
} else {
// Permission is not granted, show a dialog to ask for permission
return
}
}
val notificationBuilder = NotificationCompat.Builder(applicationContext, "News Channel ID")
.setContentTitle("News")
.setContentText("You have new updated news please check it out")
.setSmallIcon(R.drawable.news)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
notificationManager.notify(1, notificationBuilder.build())
}
}
object ServiceLocator {
lateinit var newsRepository: NewsRepository
}
`Мне нужна такая функциональность, как мое приложение, которое будет получать данные из API и обновлять данные в базе данных каждые 15-16 минут, поэтому я использую для этого периодическую задачу диспетчера работ. Но диспетчер работ работает только тогда, когда приложение находится в фоновом режиме (список последних приложений), и если я проведу пальцем вверх от списка последних приложений (фон), то менеджер работ больше не работает, и когда я запускаю свое приложение снова, тогда работает только оно. У меня аппарат самсунг ф62. Я также пытаюсь выполнить автоматический запуск в соответствии с настройками, но функция автоматического запуска не является их функцией, а оптимизация батареи не ограничена, что также не работает. Рабочий класс -: [code]@HiltWorker class NewsWorker @AssistedInject constructor( @Assisted appContext: Context, @Assisted params: WorkerParameters, ) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result { val newsRepository = ServiceLocator.newsRepository Log.d("worker call", "this is a worker call") var result: Result? = null try { newsRepository.workManagerRequest() .catch { result = Result.failure() Log.d("worker call", "this is a worker call failure from 1st catch") } .collect { flowResult -> when (flowResult) { is Results.Success -> { Log.d("worker call", "this is a worker call Success") // Handle the successful case // You can process the PagingData here showNotification() } is Results.Error -> { Log.d("worker call", "this is a worker call failure from Result.Error") // Handle the error case result = Result.failure() } } if (result != null) return@collect } } catch (e: Exception) { Log.d("worker call", "this is a worker call failure from second catch :$e") result = Result.failure() } return result ?: Result.success() }
private fun showNotification() { val notificationManager = NotificationManagerCompat.from(applicationContext) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (ContextCompat.checkSelfPermission( applicationContext, Manifest.permission.ACCESS_NOTIFICATION_POLICY ) == PackageManager.PERMISSION_GRANTED ) { // Permission is granted, proceed with creating the channel val channel = NotificationChannel( "News Channel ID", "News Channel", NotificationManager.IMPORTANCE_DEFAULT ) notificationManager.createNotificationChannel(channel) } else { // Permission is not granted, show a dialog to ask for permission return } }
val notificationBuilder = NotificationCompat.Builder(applicationContext, "News Channel ID") .setContentTitle("News") .setContentText("You have new updated news please check it out") .setSmallIcon(R.drawable.news) .setPriority(NotificationCompat.PRIORITY_DEFAULT)
Dependecy-: //dagger-hilt for worker implementation ("androidx.hilt:hilt-work:1.0.0") kapt ("androidx.hilt:hilt-compiler:1.0.0")
//Work manager implementation ("androidx.work:work-runtime-ktx:2.7.1") [/code] Настройки автоматического запуска не являются их настройками, а оптимизация батареи не ограничена, но не работает `