This commit is contained in:
Tommaso Berlose
2020-05-05 14:29:30 +02:00
parent 4feb72381d
commit f5c4ee7eb0
32 changed files with 394 additions and 228 deletions

View File

@ -8,6 +8,7 @@ import android.content.Intent
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.*
@ -19,68 +20,7 @@ class WeatherReceiver : BroadcastReceiver() {
Intent.ACTION_MY_PACKAGE_REPLACED,
Intent.ACTION_TIMEZONE_CHANGED,
Intent.ACTION_LOCALE_CHANGED,
Intent.ACTION_TIME_CHANGED -> setUpdates(context)
Actions.ACTION_WEATHER_UPDATE -> WeatherHelper.updateWeather(context)
}
}
companion object {
fun setUpdates(context: Context) {
removeUpdates(context)
if (Preferences.showWeather && Preferences.weatherProviderApi != "") {
WeatherHelper.updateWeather(context)
with(context.getSystemService(Context.ALARM_SERVICE) as AlarmManager) {
val pi = PendingIntent.getBroadcast(
context,
1,
Intent(context, WeatherReceiver::class.java).apply {
action = Actions.ACTION_WEATHER_UPDATE
},
0
)
val refresh: Long = when (Preferences.weatherRefreshPeriod) {
0 -> 30
1 -> 60
2 -> 60 * 3
3 -> 60 * 6
4 -> 60 * 12
5 -> 60 * 24
else -> 60
}
val now = Calendar.getInstance().apply {
set(Calendar.MILLISECOND, 0)
set(Calendar.SECOND, 0)
}
setRepeating(AlarmManager.RTC_WAKEUP, now.timeInMillis, 1000 * 60 * refresh, pi)
}
}
}
fun setOneTimeUpdate(context: Context) {
// Update the weather in a few minuter when the api key has been changed
with(context.getSystemService(Context.ALARM_SERVICE) as AlarmManager) {
val pi = PendingIntent.getBroadcast(context, 1, Intent(context, WeatherReceiver::class.java).apply { action = Actions.ACTION_WEATHER_UPDATE }, 0)
val now = Calendar.getInstance().apply {
set(Calendar.MILLISECOND, 0)
set(Calendar.SECOND, 0)
}
listOf(10, 15, 20).forEach {
setExact(AlarmManager.RTC_WAKEUP, now.timeInMillis + 1000 * 60 * it, pi)
}
}
}
fun removeUpdates(context: Context) {
val intent = Intent(context, WeatherReceiver::class.java)
val sender = PendingIntent.getBroadcast(context, 1, intent, 0)
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(sender)
Intent.ACTION_TIME_CHANGED -> WeatherWorker.setUpdates(context)
}
}
}