Remove workers. Fix #71

This commit is contained in:
Tommaso Berlose 2020-05-06 21:25:23 +02:00
parent 7076311e94
commit ea372dd76d
11 changed files with 61 additions and 322 deletions

Binary file not shown.

View File

@ -18,7 +18,7 @@ android {
applicationId "com.tommasoberlose.anotherwidget"
minSdkVersion 23
targetSdkVersion 29
versionCode 70
versionCode 71
versionName "2.0.5"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

BIN
app/release/app-release.aab Normal file

Binary file not shown.

View File

@ -5,7 +5,6 @@ import com.chibatching.kotpref.bulk
import com.tommasoberlose.anotherwidget.global.Preferences
import com.tommasoberlose.anotherwidget.models.Event
import com.tommasoberlose.anotherwidget.receivers.UpdatesReceiver
import com.tommasoberlose.anotherwidget.services.UpdatesWorker
import com.tommasoberlose.anotherwidget.ui.widgets.MainWidget
import io.realm.Realm
import io.realm.RealmResults

View File

@ -4,13 +4,11 @@ import android.Manifest
import android.content.ContentUris
import android.content.Context
import android.provider.CalendarContract
import android.util.Log
import com.tommasoberlose.anotherwidget.services.EventListenerJob
import com.tommasoberlose.anotherwidget.db.EventRepository
import com.tommasoberlose.anotherwidget.models.Event
import com.tommasoberlose.anotherwidget.global.Preferences
import com.tommasoberlose.anotherwidget.receivers.UpdatesReceiver
import com.tommasoberlose.anotherwidget.services.UpdatesWorker
import com.tommasoberlose.anotherwidget.ui.activities.MainActivity
import com.tommasoberlose.anotherwidget.ui.widgets.MainWidget
import com.tommasoberlose.anotherwidget.utils.checkGrantedPermission

View File

@ -5,10 +5,10 @@ import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.tommasoberlose.anotherwidget.global.Actions
import com.tommasoberlose.anotherwidget.global.Preferences
import com.tommasoberlose.anotherwidget.helpers.WeatherHelper
import com.tommasoberlose.anotherwidget.services.WeatherWorker
import java.util.*
@ -20,68 +20,63 @@ class WeatherReceiver : BroadcastReceiver() {
Intent.ACTION_MY_PACKAGE_REPLACED,
Intent.ACTION_TIMEZONE_CHANGED,
Intent.ACTION_LOCALE_CHANGED,
Intent.ACTION_TIME_CHANGED,
Actions.ACTION_WEATHER_UPDATE -> WeatherWorker.setUpdates(context)
Intent.ACTION_TIME_CHANGED -> setUpdates(context)
Actions.ACTION_WEATHER_UPDATE -> {
WeatherHelper.updateWeather(context)
}
}
}
companion object {
private const val MINUTE = 60 * 1000L
fun setUpdates(context: Context) {
removeUpdates(context)
// fun setUpdates(context: Context) {
// removeUpdates(context)
//
// if (Preferences.showWeather && Preferences.weatherProviderApi != "") {
// WeatherHelper.updateWeather(context)
// WorkManager.getInstance(context).enqueueUniquePeriodicWork(
// "WEATHER_JOB_PERIODIC",
// ExistingPeriodicWorkPolicy.KEEP,
// PeriodicWorkRequestBuilder<WeatherWorker>(
// when (Preferences.weatherRefreshPeriod) {
// 0 -> 30
// 1 -> 60
// 2 -> 60L * 3
// 3 -> 60L * 6
// 4 -> 60L * 12
// 5 -> 60L * 24
// else -> 60
// }
// , TimeUnit.MINUTES
// )
// .addTag(JOB_TAG)
// .setConstraints(constraints)
// .build()
// )
// }
// }
//
// fun setOneTimeUpdate(context: Context) {
//
// listOf(10L, 20L, 30L).forEach {
// with(context.getSystemService(Context.ALARM_SERVICE) as AlarmManager) {
// setRepeating(
// AlarmManager.RTC,
// if (event.endDate > 60 *1000) event.endDate else now.timeInMillis + 120000,
// PendingIntent.getBroadcast(context, 0, Intent(context, UpdatesReceiver::class.java).apply { action = Actions.ACTION_WEATHER_UPDATE }, 0)
// )
// }
// workManager.enqueueUniqueWork(
// "WEATHER_JOB_ONE_TIME_$it", ExistingWorkPolicy.KEEP,
// OneTimeWorkRequestBuilder<WeatherWorker>()
// .setInitialDelay(it, TimeUnit.MINUTES)
// .setConstraints(constraints)
// .addTag(JOB_TAG)
// .build()
// )
// }
// }
//
// fun removeUpdates(context: Context) {
// with(context.getSystemService(Context.ALARM_SERVICE) as AlarmManager) {
// cancel(PendingIntent.getBroadcast(context, 0, Intent(context, WeatherReceiver::class.java).apply { action = Actions.ACTION_WEATHER_UPDATE }, 0))
// listOf(10L, 20L, 30L).forEach {
// cancel(PendingIntent.getBroadcast(context, it.toInt(), Intent(context, WeatherReceiver::class.java).apply { action = Actions.ACTION_WEATHER_UPDATE }, 0))
// }
// }
// }
if (Preferences.showWeather && Preferences.weatherProviderApi != "") {
WeatherHelper.updateWeather(context)
val interval = MINUTE * when (Preferences.weatherRefreshPeriod) {
0 -> 30
1 -> 60
2 -> 60L * 3
3 -> 60L * 6
4 -> 60L * 12
5 -> 60L * 24
else -> 60
}
with(context.getSystemService(Context.ALARM_SERVICE) as AlarmManager) {
setRepeating(
AlarmManager.RTC,
Calendar.getInstance().timeInMillis + interval,
interval,
PendingIntent.getBroadcast(context, 0, Intent(context, WeatherReceiver::class.java).apply { action = Actions.ACTION_WEATHER_UPDATE }, 0)
)
}
}
}
fun setOneTimeUpdate(context: Context) {
if (Preferences.showWeather && Preferences.weatherProviderApi != "") {
listOf(10, 20, 30).forEach {
with(context.getSystemService(Context.ALARM_SERVICE) as AlarmManager) {
setExactAndAllowWhileIdle(
AlarmManager.RTC,
it * MINUTE,
PendingIntent.getBroadcast(context, it, Intent(context, WeatherReceiver::class.java).apply { action = Actions.ACTION_WEATHER_UPDATE }, 0)
)
}
}
}
}
fun removeUpdates(context: Context) {
with(context.getSystemService(Context.ALARM_SERVICE) as AlarmManager) {
cancel(PendingIntent.getBroadcast(context, 0, Intent(context, WeatherReceiver::class.java).apply { action = Actions.ACTION_WEATHER_UPDATE }, 0))
listOf(10, 20, 30).forEach {
cancel(PendingIntent.getBroadcast(context, it, Intent(context, WeatherReceiver::class.java).apply { action = Actions.ACTION_WEATHER_UPDATE }, 0))
}
}
}
}
}

View File

@ -1,154 +0,0 @@
package com.tommasoberlose.anotherwidget.services
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.work.*
import com.tommasoberlose.anotherwidget.db.EventRepository
import com.tommasoberlose.anotherwidget.global.Actions
import com.tommasoberlose.anotherwidget.models.Event
import com.tommasoberlose.anotherwidget.receivers.UpdatesReceiver
import com.tommasoberlose.anotherwidget.ui.widgets.MainWidget
import org.joda.time.Period
import java.util.*
import java.util.concurrent.TimeUnit
class UpdatesWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {
override fun doWork(): Result {
Log.d("ciao1", "update ok: $inputData")
val repo = EventRepository(applicationContext)
val event = repo.getEventByEventId(inputData.getLong(EVENT_ID, -1))
event?.let {
scheduleEventUpdate(applicationContext, it)
}
MainWidget.updateWidget(applicationContext)
return Result.success()
}
companion object {
private const val UPDATES_JOB_TAG = "UPDATES_WORKER"
private const val EVENT_ID = "event_id"
fun setUpdates(context: Context) {
removeUpdates(context)
EventRepository(context).getEvents().forEach { event ->
scheduleEventUpdate(context, event)
}
}
private fun scheduleEventUpdate(context: Context, event: Event) {
val workManager = WorkManager.getInstance(context)
val now = Calendar.getInstance().apply {
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
if (event.startDate > now.timeInMillis) {
val diff = Period(now.timeInMillis, event.startDate)
workManager.enqueueUniqueWork(
"UNIQUE_${event.eventID}",
ExistingWorkPolicy.REPLACE,
OneTimeWorkRequestBuilder<UpdatesWorker>()
.setInputData(Data.Builder().putLong(EVENT_ID, event.eventID).build())
.setInitialDelay(if (diff.minutes > 0) diff.minutes.toLong() else 60L, TimeUnit.MINUTES)
.addTag(UPDATES_JOB_TAG)
.build()
)
} else if (event.endDate > now.timeInMillis) {
// Update the widget one second after the event is finished
workManager.enqueueUniqueWork(
"UNIQUE_${event.eventID}",
ExistingWorkPolicy.REPLACE,
OneTimeWorkRequestBuilder<UpdatesWorker>()
.setInitialDelay(event.endDate - now.timeInMillis - 10 * 60 * 1000, TimeUnit.MILLISECONDS)
.addTag(UPDATES_JOB_TAG)
.build()
)
}
}
fun removeUpdates(context: Context) {
// WorkManager.getInstance(context).cancelAllWorkByTag(UPDATES_JOB_TAG)
}
}
}
//
//class UpdatesWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {
//
// override fun doWork(): Result {
// Log.d("ciao1", "update ok: $inputData")
// MainWidget.updateWidget(applicationContext)
// scheduleNextEventUpdate(applicationContext)
// return Result.success()
// }
//
// companion object {
// private const val JOB_TAG = "UPDATES_WORKER"
// private const val ONE_HOUR = 60 * 60 * 1000
//
// fun setUpdates(context: Context) {
// removeUpdates(context)
//
// scheduleNextEventUpdate(context)
// }
//
// private fun scheduleNextEventUpdate(context: Context) {
// val workManager = WorkManager.getInstance(context)
// val now = Calendar.getInstance().apply {
// set(Calendar.SECOND, 0)
// set(Calendar.MILLISECOND, 0)
// }
//
// val firstEvent = EventRepository(context).getEvents().sort("startDate").first()
// firstEvent?.let { event ->
// if (event.startDate < now.timeInMillis) {
// // Update the widget one second after the event is finished
// workManager.enqueue(OneTimeWorkRequestBuilder<UpdatesWorker>()
// .setInitialDelay((if (event.endDate - now.timeInMillis < ONE_HOUR) event.endDate - now.timeInMillis else ONE_HOUR).toLong(), TimeUnit.MILLISECONDS)
// .addTag(JOB_TAG)
// .build()
// )
//
// } else {
// val diff = Period(now.timeInMillis, event.startDate)
// workManager.enqueue(OneTimeWorkRequestBuilder<UpdatesWorker>()
// .setInitialDelay(if (diff.minutes > 0) diff.minutes.toLong() else 60L, TimeUnit.MINUTES)
// .addTag(JOB_TAG)
// .build()
// )
// Log.d("ciao1", "next update ${Date(now.timeInMillis + (if (diff.minutes > 0) diff.minutes.toLong() else 60L) * 60 * 1000)}")
// }
// }
//
//
//// if (event.startDate > now.timeInMillis) {
//// val diff = Period(now.timeInMillis, event.startDate)
//// workManager.enqueue(OneTimeWorkRequestBuilder<WeatherWorker>()
//// .setInputData(Data.Builder().putLong(EVENT_ID, event.eventID).build())
//// .setInitialDelay(if (diff.minutes > 0) diff.minutes.toLong() else 60L, TimeUnit.MINUTES)
//// .addTag(JOB_TAG)
//// .build()
//// )
//// Log.d("ciao1", "next update ${Date(now.timeInMillis + (if (diff.minutes > 0) diff.minutes.toLong() else 60L) * 60 * 1000)}")
//// } else if (event.endDate > now.timeInMillis) {
//// // Update the widget one second after the event is finished
//// workManager.enqueueUniqueWork("UPDATES_JOB_ONE_TIME_END_${event.eventID}", ExistingWorkPolicy.REPLACE, OneTimeWorkRequestBuilder<WeatherWorker>()
//// .setInitialDelay(event.endDate - now.timeInMillis, TimeUnit.MILLISECONDS)
//// .addTag(JOB_TAG)
//// .build()
//// )
//// }
// }
//
// fun removeUpdates(context: Context) {
// WorkManager.getInstance(context).cancelAllWorkByTag(JOB_TAG)
// }
// }
//}

View File

@ -1,77 +0,0 @@
package com.tommasoberlose.anotherwidget.services
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.work.*
import com.tommasoberlose.anotherwidget.global.Actions
import com.tommasoberlose.anotherwidget.global.Preferences
import com.tommasoberlose.anotherwidget.helpers.WeatherHelper
import com.tommasoberlose.anotherwidget.receivers.WeatherReceiver
import java.util.*
import java.util.concurrent.TimeUnit
class WeatherWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {
override fun doWork(): Result {
Log.d("ciao1", "weather ok")
WeatherHelper.updateWeather(applicationContext)
return Result.success()
}
companion object {
private const val JOB_TAG = "WEATHER_WORKER"
fun setUpdates(context: Context) {
removeUpdates(context)
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
if (Preferences.showWeather && Preferences.weatherProviderApi != "") {
WeatherHelper.updateWeather(context)
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
"WEATHER_JOB_PERIODIC",
ExistingPeriodicWorkPolicy.KEEP,
PeriodicWorkRequestBuilder<WeatherWorker>(
when (Preferences.weatherRefreshPeriod) {
0 -> 30
1 -> 60
2 -> 60L * 3
3 -> 60L * 6
4 -> 60L * 12
5 -> 60L * 24
else -> 60
}
, TimeUnit.MINUTES
)
.addTag(JOB_TAG)
.setConstraints(constraints)
.build()
)
}
}
fun setOneTimeUpdate(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val workManager = WorkManager.getInstance(context)
listOf(10L, 20L, 30L).forEach {
workManager.enqueueUniqueWork("WEATHER_JOB_ONE_TIME_$it", ExistingWorkPolicy.KEEP,
OneTimeWorkRequestBuilder<WeatherWorker>()
.setInitialDelay(it, TimeUnit.MINUTES)
.setConstraints(constraints)
.addTag(JOB_TAG)
.build()
)
}
}
fun removeUpdates(context: Context) {
WorkManager.getInstance(context).cancelAllWorkByTag(JOB_TAG)
}
}
}

View File

@ -3,36 +3,25 @@ package com.tommasoberlose.anotherwidget.ui.activities
import android.Manifest
import android.animation.ValueAnimator
import android.app.Activity
import android.app.AlarmManager
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.animation.addListener
import androidx.core.app.AlarmManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.work.OneTimeWorkRequest
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import com.google.android.material.badge.BadgeDrawable
import com.google.android.material.tabs.TabLayoutMediator
import com.kwabenaberko.openweathermaplib.models.common.Weather
import com.tommasoberlose.anotherwidget.R
import com.tommasoberlose.anotherwidget.components.MaterialBottomSheetDialog
import com.tommasoberlose.anotherwidget.global.Actions
@ -40,27 +29,21 @@ import com.tommasoberlose.anotherwidget.global.Constants
import com.tommasoberlose.anotherwidget.global.Preferences
import com.tommasoberlose.anotherwidget.global.RequestCode
import com.tommasoberlose.anotherwidget.helpers.BitmapHelper
import com.tommasoberlose.anotherwidget.helpers.CalendarHelper
import com.tommasoberlose.anotherwidget.helpers.ColorHelper
import com.tommasoberlose.anotherwidget.helpers.ColorHelper.isColorDark
import com.tommasoberlose.anotherwidget.helpers.WeatherHelper
import com.tommasoberlose.anotherwidget.receivers.UpdatesReceiver
import com.tommasoberlose.anotherwidget.services.UpdatesWorker
import com.tommasoberlose.anotherwidget.services.WeatherWorker
import com.tommasoberlose.anotherwidget.ui.adapters.ViewPagerAdapter
import com.tommasoberlose.anotherwidget.ui.viewmodels.MainViewModel
import com.tommasoberlose.anotherwidget.ui.widgets.MainWidget
import com.tommasoberlose.anotherwidget.utils.checkGrantedPermission
import com.tommasoberlose.anotherwidget.utils.getCurrentWallpaper
import com.tommasoberlose.anotherwidget.utils.toPixel
import com.tommasoberlose.anotherwidget.utils.toast
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.the_widget_sans.*
import kotlinx.coroutines.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*
class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {

View File

@ -29,7 +29,6 @@ import com.tommasoberlose.anotherwidget.global.Preferences
import com.tommasoberlose.anotherwidget.global.RequestCode
import com.tommasoberlose.anotherwidget.helpers.SettingsStringHelper
import com.tommasoberlose.anotherwidget.receivers.WeatherReceiver
import com.tommasoberlose.anotherwidget.services.WeatherWorker
import com.tommasoberlose.anotherwidget.ui.activities.ChooseApplicationActivity
import com.tommasoberlose.anotherwidget.ui.activities.CustomLocationActivity
import com.tommasoberlose.anotherwidget.ui.activities.MainActivity
@ -143,7 +142,7 @@ class WeatherSettingsFragment : Fragment() {
if (activity?.checkGrantedPermission(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) Manifest.permission.ACCESS_BACKGROUND_LOCATION else Manifest.permission.ACCESS_FINE_LOCATION) == true) {
location_permission_alert?.isVisible = false
WeatherWorker.setUpdates(requireContext())
WeatherReceiver.setUpdates(requireContext())
} else if (Preferences.showWeather && Preferences.customLocationAdd == "") {
location_permission_alert?.isVisible = true
location_permission_alert?.setOnClickListener {
@ -218,7 +217,7 @@ class WeatherSettingsFragment : Fragment() {
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
Constants.RESULT_CODE_CUSTOM_LOCATION -> {
WeatherWorker.setUpdates(requireContext())
WeatherReceiver.setUpdates(requireContext())
checkLocationPermission()
}
RequestCode.WEATHER_APP_REQUEST_CODE.code -> {
@ -229,7 +228,7 @@ class WeatherSettingsFragment : Fragment() {
MainWidget.updateWidget(requireContext())
}
RequestCode.WEATHER_PROVIDER_REQUEST_CODE.code -> {
WeatherWorker.setOneTimeUpdate(requireContext())
WeatherReceiver.setOneTimeUpdate(requireContext())
}
}
}

View File

@ -12,7 +12,6 @@ import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.text.format.DateUtils
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.widget.ImageView
@ -27,17 +26,14 @@ import com.tommasoberlose.anotherwidget.global.Actions
import com.tommasoberlose.anotherwidget.global.Constants
import com.tommasoberlose.anotherwidget.global.Preferences
import com.tommasoberlose.anotherwidget.helpers.*
import com.tommasoberlose.anotherwidget.helpers.WidgetHelper.reduceDimensionWithMaxWidth
import com.tommasoberlose.anotherwidget.receivers.NewCalendarEventReceiver
import com.tommasoberlose.anotherwidget.receivers.UpdatesReceiver
import com.tommasoberlose.anotherwidget.receivers.WeatherReceiver
import com.tommasoberlose.anotherwidget.receivers.WidgetClickListenerReceiver
import com.tommasoberlose.anotherwidget.services.UpdatesWorker
import com.tommasoberlose.anotherwidget.services.WeatherWorker
import com.tommasoberlose.anotherwidget.utils.checkGrantedPermission
import com.tommasoberlose.anotherwidget.utils.getCapWordString
import com.tommasoberlose.anotherwidget.utils.toPixel
import kotlinx.android.synthetic.main.the_widget.view.*
import kotlinx.android.synthetic.main.the_widget_sans.*
import java.lang.Exception
import java.text.DateFormat
import java.util.*
@ -59,7 +55,7 @@ class MainWidget : AppWidgetProvider() {
override fun onEnabled(context: Context) {
CalendarHelper.updateEventList(context)
WeatherWorker.setUpdates(context)
WeatherReceiver.setUpdates(context)
if (Preferences.showEvents) {
CalendarHelper.setEventUpdatesAndroidN(context)
@ -71,7 +67,7 @@ class MainWidget : AppWidgetProvider() {
override fun onDisabled(context: Context) {
if (getWidgetCount(context) == 0) {
UpdatesReceiver.removeUpdates(context)
WeatherWorker.removeUpdates(context)
WeatherReceiver.removeUpdates(context)
}
}