#android #kotlin #android-workmanager
#Android #kotlin #android-workmanager
Вопрос:
Я пытаюсь выполнить одноразовое задание с WorkManager. Я не знаю почему, но если я закрою свое приложение из меню последних приложений, задание не запускается, пока я не запущу приложение:/. Пробовал с samsung Galaxy s9 . Android 9 Pie. Любая помощь будет оценена. Насколько я знаю, workmanager должен работать даже при перезапуске телефона.
val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.NOT_REQUIRED).build()
val request = OneTimeWorkRequestBuilder<NotificationJob>()
.addTag(item.uniqueId)
.setInputData(data)
.setConstraints(constraints)
//TODO revert
// .setInitialDelay(warrantyItem.reminderDate - System.currentTimeMillis(), TimeUnit.MILLISECONDS)
.setInitialDelay(1, TimeUnit.MINUTES)
.build()
WorkManager.getInstance(this@MainActivity).enqueue(request)
задание довольно простое. Просто уведомление:
override fun doWork(): Result {
// Get the input
val uniqueId = inputData.getString(JOB_KEY)
if (uniqueId != null) {
sendNotification(uniqueId, "title", "subtitle")
}
return Result.success()
}
private fun sendNotification(uniqueId: String, title: String, subtitle: String) {
val intent = Intent(applicationContext, MainActivity::class.java)
intent.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK
intent.putExtra(NOTIFICATION_ID, id)
val notificationManager =
applicationContext.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
val bitmap = applicationContext.vectorToBitmap(R.drawable.ic_warranty_icon)
val titleNotification = "$title"
val subtitleNotification = subtitle
val pendingIntent = getActivity(applicationContext, 0, intent, 0)
val notification = NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL)
.setLargeIcon(bitmap).setSmallIcon(R.drawable.ic_warranty_icon)
.setContentTitle(titleNotification).setContentText(subtitleNotification)
.setDefaults(DEFAULT_ALL).setContentIntent(pendingIntent).setAutoCancel(true)
notification.priority = PRIORITY_MAX
if (SDK_INT >= O) {
notification.setChannelId(NOTIFICATION_CHANNEL)
val ringtoneManager = getDefaultUri(TYPE_NOTIFICATION)
val audioAttributes = AudioAttributes.Builder().setUsage(USAGE_NOTIFICATION_RINGTONE)
.setContentType(CONTENT_TYPE_SONIFICATION).build()
val channel =
NotificationChannel(NOTIFICATION_CHANNEL, NOTIFICATION_NAME, IMPORTANCE_HIGH)
channel.enableLights(true)
channel.lightColor = RED
channel.enableVibration(true)
channel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
channel.setSound(ringtoneManager, audioAttributes)
notificationManager.createNotificationChannel(channel)
}
with(NotificationManagerCompat.from(applicationContext)) {
// notificationId is a unique int for each notification that you must define
notify(uniqueId, ID, notification.build())
}
}
Комментарии:
1. Привет! Отправляете ли вы строковое значение «JOB_KEY» в менеджер работ?
2. Да, все работает правильно, пока приложение не закрыто
3. Если вы тестируете свое приложение, запуская его из Android Studio, оно может вести себя иначе, чем при запуске с устройства. Сказал, что было бы полезно иметь больше информации о регистрации, как описано в этом codelab: codelabs.developers.google.com/codelabs/android-adv-workmanager /…