Fixed time drift issue when setting wallpaper https://github.com/Anthonyy232/Paperize/issues/343

This commit is contained in:
Anthonyy232 committed 2025-08-19 16:49:28 -07:00
1 parent 83cc89e1b3
commit c9e485ac88
8 files changed
+377 -557

No files matched your search

@@ -116,7 +116,7 @@ class MainActivity : ComponentActivity() {
val settingsState = settingsViewModel.state.collectAsStateWithLifecycle()
val isFirstLaunch = runBlocking { settingsDataStoreImpl.getBoolean(SettingsConstants.FIRST_LAUNCH) } ?: true
val scheduler = WallpaperAlarmSchedulerImpl(this)
val scheduler = WallpaperAlarmSchedulerImpl(this, settingsDataStoreImpl)
var hasScheduleRun by remember { mutableStateOf(false) }
LaunchedEffect(settingsState.value) {
@@ -247,4 +247,3 @@ class MainActivity : ComponentActivity() {
return pendingIntent != null
}
}
@@ -131,7 +131,8 @@ fun PaperizeApp(
homeInterval = timeInMinutes
)
),
scheduler = scheduler
scheduler = scheduler,
context = context
)
}
},
@@ -145,7 +146,8 @@ fun PaperizeApp(
lockInterval = timeInMinutes
)
),
scheduler = scheduler
scheduler = scheduler,
context = context
)
}
},
@@ -190,6 +192,7 @@ fun PaperizeApp(
),
settingsViewModel = settingsViewModel,
scheduler = scheduler,
context = context,
refreshNextTime = true
)
}
@@ -232,6 +235,7 @@ fun PaperizeApp(
),
settingsViewModel = settingsViewModel,
scheduler = scheduler,
context = context,
refreshNextTime = true,
changeImmediate = true,
cancelImmediate = true,
@@ -305,7 +309,8 @@ fun PaperizeApp(
)
),
settingsViewModel = settingsViewModel,
scheduler = scheduler
scheduler = scheduler,
context = context
)
}
else if (albumState.value.selectedAlbum.isNotEmpty() && settingsState.value.wallpaperSettings.enableChanger) {
@@ -317,7 +322,8 @@ fun PaperizeApp(
)
),
settingsViewModel = settingsViewModel,
scheduler = scheduler
scheduler = scheduler,
context = context
)
}
},
@@ -343,7 +349,8 @@ fun PaperizeApp(
)
),
settingsViewModel = settingsViewModel,
scheduler = scheduler
scheduler = scheduler,
context = context
)
}
else if (albumState.value.selectedAlbum.isNotEmpty() && settingsState.value.wallpaperSettings.enableChanger) {
@@ -355,7 +362,8 @@ fun PaperizeApp(
)
),
settingsViewModel = settingsViewModel,
scheduler = scheduler
scheduler = scheduler,
context = context
)
}
},
@@ -371,6 +379,7 @@ fun PaperizeApp(
),
settingsViewModel = settingsViewModel,
scheduler = scheduler,
context = context,
changeImmediate = true,
cancelImmediate = true,
firstLaunch = true
@@ -473,7 +482,8 @@ fun PaperizeApp(
scheduleSettings = settingsState.value.scheduleSettings.copy(
startTime = Pair(time.hour, time.minute))
),
scheduler = scheduler
scheduler = scheduler,
context = context
)
}
},
@@ -487,7 +497,8 @@ fun PaperizeApp(
changeStartTime = changeStartTime
)
),
scheduler = scheduler
scheduler = scheduler,
context = context
)
}
},
@@ -501,14 +512,15 @@ fun PaperizeApp(
shuffle = shuffle
)
),
scheduler = scheduler
scheduler = scheduler,
context = context
)
}
},
onRefreshChange = { refresh ->
settingsViewModel.onEvent(SettingsEvent.SetRefresh(refresh))
if (settingsState.value.wallpaperSettings.enableChanger) {
scheduler.scheduleRefresh(refresh)
WallpaperAlarmSchedulerImpl.scheduleRefresh(context, refresh)
}
},
onSkipLandscapeChange = { skipLandscape ->
@@ -691,6 +703,7 @@ private fun CoroutineScope.scheduleWallpaperUpdate(
settingsState: SettingsState,
settingsViewModel: SettingsViewModel,
scheduler: WallpaperAlarmSchedulerImpl,
context: android.content.Context,
refreshNextTime: Boolean = false,
changeImmediate: Boolean = true,
cancelImmediate: Boolean = true,
@@ -723,7 +736,7 @@ private fun CoroutineScope.scheduleWallpaperUpdate(
cancelImmediate = cancelImmediate,
firstLaunch = firstLaunch
)
scheduler.scheduleRefresh(settingsState.scheduleSettings.refresh)
WallpaperAlarmSchedulerImpl.scheduleRefresh(context, settingsState.scheduleSettings.refresh)
}
}
@@ -731,6 +744,7 @@ private fun CoroutineScope.updateWallpaperAlarm(
job: Job?,
settingsState: SettingsState,
scheduler: WallpaperAlarmSchedulerImpl,
context: android.content.Context,
firstLaunch: Boolean = true,
): Job {
job?.cancel()
@@ -750,7 +764,7 @@ private fun CoroutineScope.updateWallpaperAlarm(
wallpaperAlarmItem = alarmItem,
firstLaunch = firstLaunch
)
scheduler.scheduleRefresh(settingsState.scheduleSettings.refresh)
WallpaperAlarmSchedulerImpl.scheduleRefresh(context, settingsState.scheduleSettings.refresh)
}
}
@@ -1,18 +1,27 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager
import android.Manifest
import android.app.AlarmManager
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.AlarmManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresPermission
import androidx.core.app.NotificationCompat
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.core.Type
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.presentation.MainActivity
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.HomeWallpaperService
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.LockWallpaperService
import dagger.hilt.android.qualifiers.ApplicationContext
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import javax.inject.Inject
data class ServiceConfig(
@@ -27,19 +36,54 @@ sealed class WallpaperAction {
data object UPDATE : WallpaperAction()
}
/**
* This class is responsible for scheduling wallpaper alarms.
* It uses the AlarmManager to schedule alarms for the [WallpaperReceiver].
* It also uses [HomeWallpaperService] and [LockWallpaperService] to change the wallpaper due to receiver limitations.
*/
class WallpaperAlarmSchedulerImpl @Inject constructor(
private val context: Context
@param:ApplicationContext private val context: Context,
private val settingsDataStore: SettingsDataStore
): WallpaperAlarmScheduler {
private val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
/**
* Schedules the wallpaper alarm based on the origin and changeImmediate
*/
companion object {
private const val TAG = "WallpaperAlarmScheduler"
/**
* Schedules a refresh alarm every 24hrs
* This is a static method that doesn't require an instance of WallpaperAlarmSchedulerImpl
*/
fun scheduleRefresh(context: Context, refresh: Boolean = true) {
Log.d(TAG, "scheduleRefresh called with refresh: $refresh")
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// Cancel any existing refresh alarm
val cancelIntent = Intent(context, WallpaperReceiver::class.java)
val cancelPendingIntent = PendingIntent.getBroadcast(
context,
Type.REFRESH.ordinal,
cancelIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
alarmManager.cancel(cancelPendingIntent)
if (refresh) {
val intent = Intent(context, WallpaperReceiver::class.java).apply {
putExtra("refresh", true)
}
val nextMidnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0)
Log.d(TAG, "Scheduling inexact repeating refresh alarm for next midnight: $nextMidnight")
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
nextMidnight.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000,
AlarmManager.INTERVAL_DAY,
PendingIntent.getBroadcast(
context,
Type.REFRESH.ordinal,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
)
}
}
}
@RequiresPermission(Manifest.permission.SCHEDULE_EXACT_ALARM)
override suspend fun scheduleWallpaperAlarm(
wallpaperAlarmItem: WallpaperAlarmItem,
@@ -51,9 +95,14 @@ class WallpaperAlarmSchedulerImpl @Inject constructor(
homeNextTime: String?,
lockNextTime: String?,
) {
// Cancel previous alarms before setting new ones to prevent stale alarms
if (cancelImmediate) cancelWallpaperAlarm()
else {
Log.d(TAG, "scheduleWallpaperAlarm called with:")
Log.d(TAG, " - wallpaperAlarmItem: $wallpaperAlarmItem")
Log.d(TAG, " - changeImmediate: $changeImmediate, setAlarm: $setAlarm, firstLaunch: $firstLaunch")
if (cancelImmediate) {
Log.d(TAG, "Cancelling all previous alarms.")
cancelWallpaperAlarm()
} else {
when (origin) {
Type.HOME.ordinal -> cancelAlarm(Type.HOME)
Type.LOCK.ordinal -> cancelAlarm(Type.LOCK)
@@ -65,160 +114,179 @@ class WallpaperAlarmSchedulerImpl @Inject constructor(
}
}
// Schedule new wallpaper alarm
if (wallpaperAlarmItem.scheduleSeparately) {
when (origin) {
Type.LOCK.ordinal -> {
if (changeImmediate) changeWallpaperImmediate(wallpaperAlarmItem, Type.LOCK)
if (setAlarm) scheduleWallpaper(wallpaperAlarmItem, Type.LOCK, origin, firstLaunch, homeNextTime, lockNextTime)
}
Type.HOME.ordinal -> {
if (changeImmediate) changeWallpaperImmediate(wallpaperAlarmItem, Type.HOME)
if (setAlarm) scheduleWallpaper(wallpaperAlarmItem, Type.HOME, origin, firstLaunch, homeNextTime, lockNextTime)
}
null -> {
if (changeImmediate) {
changeWallpaperImmediate(wallpaperAlarmItem, Type.LOCK)
changeWallpaperImmediate(wallpaperAlarmItem, Type.HOME)
}
if (setAlarm) {
scheduleWallpaper(wallpaperAlarmItem, Type.LOCK, Type.LOCK.ordinal, firstLaunch, homeNextTime, lockNextTime)
scheduleWallpaper(wallpaperAlarmItem, Type.HOME, Type.HOME.ordinal, firstLaunch, homeNextTime, lockNextTime)
}
}
if (changeImmediate) {
if (wallpaperAlarmItem.scheduleSeparately) {
changeWallpaperImmediate(wallpaperAlarmItem, Type.LOCK)
changeWallpaperImmediate(wallpaperAlarmItem, Type.HOME)
} else {
changeWallpaperImmediate(wallpaperAlarmItem, Type.SINGLE)
}
}
else {
if (changeImmediate) changeWallpaperImmediate(wallpaperAlarmItem, Type.SINGLE)
if (setAlarm) scheduleWallpaper(wallpaperAlarmItem, Type.SINGLE, null, firstLaunch, homeNextTime, lockNextTime)
if (setAlarm) {
if (wallpaperAlarmItem.scheduleSeparately) {
scheduleWallpaper(wallpaperAlarmItem, Type.LOCK, Type.LOCK.ordinal, firstLaunch, homeNextTime, lockNextTime)
scheduleWallpaper(wallpaperAlarmItem, Type.HOME, Type.HOME.ordinal, firstLaunch, homeNextTime, lockNextTime)
} else {
scheduleWallpaper(wallpaperAlarmItem, Type.SINGLE, null, firstLaunch, homeNextTime, lockNextTime)
}
}
}
/**
* Update the alarms
*/
override fun updateWallpaperAlarm(wallpaperAlarmItem: WallpaperAlarmItem, firstLaunch: Boolean) {
cancelWallpaperAlarm()
if (wallpaperAlarmItem.scheduleSeparately) {
scheduleWallpaper(wallpaperAlarmItem, Type.LOCK, null, firstLaunch, "", "")
scheduleWallpaper(wallpaperAlarmItem, Type.HOME, null, firstLaunch, "", "")
}
else {
scheduleWallpaper(wallpaperAlarmItem, Type.SINGLE, null, firstLaunch, "", "")
}
}
/**
* Update the wallpaper without scheduling alarms
*/
override fun updateWallpaper(scheduleSeparately: Boolean, setHome: Boolean, setLock: Boolean) {
if (scheduleSeparately) {
updateWallpaper(Type.LOCK, setHome, setLock)
updateWallpaper(Type.HOME, setHome, setLock)
}
else {
updateWallpaper(Type.SINGLE, setHome, setLock)
}
}
/**
* Cancels all active alarms
*/
override fun cancelWallpaperAlarm(cancelLock: Boolean, cancelHome: Boolean) {
if (cancelLock) cancelAlarm(Type.LOCK)
if (cancelHome) cancelAlarm(Type.HOME)
if (cancelLock && cancelHome) {
cancelAlarm(Type.SINGLE)
cancelAlarm(Type.REFRESH)
}
}
/**
* Schedules the wallpaper alarm based on type and time
*/
@RequiresPermission(Manifest.permission.SCHEDULE_EXACT_ALARM)
private fun scheduleWallpaper(wallpaperAlarmItem: WallpaperAlarmItem, type: Type, origin: Int? = null, firstLaunch: Boolean = false, homeNextTime: String? = null, lockNextTime: String? = null) {
private suspend fun scheduleWallpaper(
wallpaperAlarmItem: WallpaperAlarmItem,
type: Type,
origin: Int? = null,
firstLaunch: Boolean = false,
homeNextTime: String? = null,
lockNextTime: String? = null
) {
Log.d(TAG, "scheduleWallpaper called for type: $type")
try {
val nextTime = calculateNextAlarmTime(wallpaperAlarmItem, type, firstLaunch, homeNextTime ?: "", lockNextTime ?: "")
Log.d(TAG, "Calculated next alarm time for type '$type': $nextTime")
val intent = createWallpaperIntent(wallpaperAlarmItem, type, origin)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (!alarmManager.canScheduleExactAlarms()) {
cancelWallpaperAlarm()
return
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !alarmManager.canScheduleExactAlarms()) {
Log.w(TAG, "Cannot schedule exact alarms. Permission may be denied.")
cancelWallpaperAlarm()
return
}
scheduleExactAlarm(nextTime, intent)
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
when (type) {
Type.HOME -> settingsDataStore.putString(SettingsConstants.HOME_NEXT_SET_TIME, nextTime.toString())
Type.LOCK -> settingsDataStore.putString(SettingsConstants.LOCK_NEXT_SET_TIME, nextTime.toString())
Type.SINGLE -> {
settingsDataStore.putString(SettingsConstants.HOME_NEXT_SET_TIME, nextTime.toString())
settingsDataStore.putString(SettingsConstants.LOCK_NEXT_SET_TIME, nextTime.toString())
}
else -> {}
}
if (firstLaunch) {
val currentTime = LocalDateTime.now()
settingsDataStore.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
}
val currentHomeNext = settingsDataStore.getString(SettingsConstants.HOME_NEXT_SET_TIME)
val currentLockNext = settingsDataStore.getString(SettingsConstants.LOCK_NEXT_SET_TIME)
val nextHomeDateTime = runCatching { LocalDateTime.parse(currentHomeNext) }.getOrNull()
val nextLockDateTime = runCatching { LocalDateTime.parse(currentLockNext) }.getOrNull()
val nextSetTimeForNotification = listOfNotNull(nextHomeDateTime, nextLockDateTime)
.filter { it.isAfter(LocalDateTime.now()) }
.minOrNull() ?: nextTime
settingsDataStore.putString(SettingsConstants.NEXT_SET_TIME, nextSetTimeForNotification.format(formatter))
postNotification(nextSetTimeForNotification)
} catch (e: Exception) {
Log.e("WallpaperAlarmScheduler", "Error scheduling wallpaper alarm: ${e.message}")
Log.e(TAG, "Error scheduling wallpaper alarm for type '$type'", e)
cancelWallpaperAlarm()
}
}
private fun calculateNextAlarmTime(wallpaperAlarmItem: WallpaperAlarmItem, type: Type, firstLaunch: Boolean, homeNextTime: String, lockNextTime: String): LocalDateTime {
val startTime = LocalDateTime.now()
private fun calculateNextAlarmTime(
wallpaperAlarmItem: WallpaperAlarmItem,
type: Type,
firstLaunch: Boolean,
homeNextTime: String,
lockNextTime: String
): LocalDateTime {
val now = LocalDateTime.now()
val intervalMinutes = when {
type == Type.LOCK && wallpaperAlarmItem.scheduleSeparately -> wallpaperAlarmItem.lockInterval.toLong()
else -> wallpaperAlarmItem.homeInterval.toLong()
}
if (firstLaunch) {
if (wallpaperAlarmItem.changeStartTime) {
return startTime.withHour(wallpaperAlarmItem.startTime.first)
.withMinute(wallpaperAlarmItem.startTime.second)
.let { if (it.isBefore(startTime)) it.plusDays(1) else it }
.withSecond(0)
.withNano(0)
val nextTime = if (wallpaperAlarmItem.changeStartTime) {
var anchorTime = now
.withHour(wallpaperAlarmItem.startTime.first)
.withMinute(wallpaperAlarmItem.startTime.second)
.withSecond(0).withNano(0)
while (!anchorTime.isAfter(now)) {
anchorTime = anchorTime.plusMinutes(intervalMinutes)
}
return when {
type == Type.LOCK && wallpaperAlarmItem.scheduleSeparately ->
startTime.plusMinutes(wallpaperAlarmItem.lockInterval.toLong()).withSecond(0).withNano(0)
type == Type.HOME && wallpaperAlarmItem.scheduleSeparately ->
startTime.plusMinutes(wallpaperAlarmItem.homeInterval.toLong()).withSecond(0).withNano(0).plusSeconds(10)
else -> startTime.plusMinutes(wallpaperAlarmItem.homeInterval.toLong()).withSecond(0).withNano(0)
anchorTime
} else {
if (firstLaunch) {
now.plusMinutes(intervalMinutes)
} else {
val baseTime = when (type) {
Type.LOCK -> runCatching { LocalDateTime.parse(lockNextTime) }.getOrDefault(now)
else -> runCatching { LocalDateTime.parse(homeNextTime) }.getOrDefault(now)
}
var futureTime = baseTime.plusMinutes(intervalMinutes)
while (!futureTime.isAfter(now)) {
futureTime = futureTime.plusMinutes(intervalMinutes)
}
futureTime
}
}
else {
fun calculateFutureTime(baseTime: LocalDateTime, intervalMinutes: Long, addSeconds: Int = 0, depth: Int = 0): LocalDateTime {
if (depth > 100) {
return startTime.plusMinutes(intervalMinutes)
}
var nextTime = baseTime.plusMinutes(intervalMinutes).withSecond(0).withNano(0)
if (addSeconds > 0) nextTime = nextTime.plusSeconds(addSeconds.toLong())
return if (nextTime.isBefore(startTime)) {
calculateFutureTime(nextTime, intervalMinutes, addSeconds, depth + 1)
} else nextTime
}
val nextTime = when {
type == Type.LOCK && wallpaperAlarmItem.scheduleSeparately -> {
val baseTime = try {
if (lockNextTime.isEmpty()) startTime else LocalDateTime.parse(lockNextTime)
} catch (e: Exception) {
startTime
}
calculateFutureTime(baseTime, wallpaperAlarmItem.lockInterval.toLong())
}
type == Type.HOME && wallpaperAlarmItem.scheduleSeparately -> {
val baseTime = try {
if (homeNextTime.isEmpty()) startTime else LocalDateTime.parse(homeNextTime)
} catch (e: Exception) {
startTime
}
calculateFutureTime(baseTime, wallpaperAlarmItem.homeInterval.toLong(), 10)
}
else -> {
val baseTime = try {
if (homeNextTime.isEmpty()) startTime else LocalDateTime.parse(homeNextTime)
} catch (e: Exception) {
startTime
}
calculateFutureTime(baseTime, wallpaperAlarmItem.homeInterval.toLong())
}
}
return nextTime.withSecond(0).withNano(0)
return if (type == Type.HOME && wallpaperAlarmItem.scheduleSeparately) {
nextTime.plusSeconds(10).withSecond(0).withNano(0)
} else {
nextTime.withSecond(0).withNano(0)
}
}
private fun changeWallpaperImmediate(wallpaperAlarmItem: WallpaperAlarmItem, type: Type) {
Log.d(TAG, "changeWallpaperImmediate called for type: $type")
val serviceConfig = ServiceConfig(
homeInterval = wallpaperAlarmItem.homeInterval,
lockInterval = wallpaperAlarmItem.lockInterval,
scheduleSeparately = wallpaperAlarmItem.scheduleSeparately
)
when (type.ordinal) {
Type.SINGLE.ordinal -> {
if (wallpaperAlarmItem.setLock) startService(context, LockWallpaperService::class.java, WallpaperAction.START, serviceConfig.copy(type = Type.SINGLE.ordinal))
if (wallpaperAlarmItem.setHome) startService(context, HomeWallpaperService::class.java, WallpaperAction.START, serviceConfig.copy(type = Type.SINGLE.ordinal))
}
Type.LOCK.ordinal -> startService(context, LockWallpaperService::class.java, WallpaperAction.START, serviceConfig.copy(type = Type.LOCK.ordinal))
Type.HOME.ordinal -> startService(context, HomeWallpaperService::class.java, WallpaperAction.START, serviceConfig.copy(type = Type.HOME.ordinal))
}
}
private fun startService(context: Context, serviceClass: Class<*>, action: WallpaperAction, config: ServiceConfig?) {
Log.d(TAG, "startService for ${serviceClass.simpleName}, action: ${action.javaClass.simpleName}")
val serviceIntent = Intent(context, serviceClass).apply {
this.action = action.javaClass.simpleName
config?.let {
it.homeInterval?.let { interval -> putExtra("homeInterval", interval) }
it.lockInterval?.let { interval -> putExtra("lockInterval", interval) }
it.scheduleSeparately?.let { separate -> putExtra("scheduleSeparately", separate) }
it.type?.let { type -> putExtra("type", type) }
}
}
context.startForegroundService(serviceIntent)
}
private fun postNotification(nextSetTime: LocalDateTime) {
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val formattedNextSetTime = nextSetTime.format(formatter)
val mainActivityIntent = Intent(context, MainActivity::class.java)
val pendingMainActivityIntent = PendingIntent.getActivity(
context, 3, mainActivityIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
val notification = NotificationCompat.Builder(context, "wallpaper_service_channel").apply {
setContentTitle(context.getString(R.string.app_name))
setContentText(context.getString(R.string.next_wallpaper_change, formattedNextSetTime))
setSmallIcon(R.drawable.notification_icon)
setContentIntent(pendingMainActivityIntent)
priority = NotificationCompat.PRIORITY_DEFAULT
setOnlyAlertOnce(true)
}.build()
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
}
private fun createWallpaperIntent(wallpaperAlarmItem: WallpaperAlarmItem, type: Type, origin: Int?): Intent {
return Intent(context, WallpaperReceiver::class.java).apply {
putExtra("homeInterval", wallpaperAlarmItem.homeInterval)
@@ -229,88 +297,30 @@ class WallpaperAlarmSchedulerImpl @Inject constructor(
putExtra("origin", origin)
putExtra("type", type.ordinal)
putExtra("changeStartTime", wallpaperAlarmItem.changeStartTime)
putExtra("startTime", intArrayOf(wallpaperAlarmItem.startTime.first, wallpaperAlarmItem.startTime.second))
}
}
@RequiresPermission(Manifest.permission.SCHEDULE_EXACT_ALARM)
private fun scheduleExactAlarm(nextTime: LocalDateTime, intent: Intent) {
val requestCode = intent.getIntExtra("type", 0)
val pendingIntent = PendingIntent.getBroadcast(
context,
intent.getIntExtra("type", 0),
requestCode,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
val triggerAtMillis = nextTime.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000
Log.d(TAG, "Setting exact alarm for $nextTime (Millis: $triggerAtMillis) with requestCode: $requestCode")
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
nextTime.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000,
triggerAtMillis,
pendingIntent
)
}
/**
* Schedules a refresh alarm every 24hrs
*/
fun scheduleRefresh(refresh: Boolean = true) {
cancelAlarm(Type.REFRESH)
if (refresh) {
val intent = Intent(context, WallpaperReceiver::class.java).apply {
putExtra("refresh", true)
}
val nextMidnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0)
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
nextMidnight.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000,
AlarmManager.INTERVAL_DAY,
PendingIntent.getBroadcast(
context,
Type.REFRESH.ordinal,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
)
}
}
/**
* Use the service to change the wallpaper
*/
private fun changeWallpaperImmediate(wallpaperAlarmItem: WallpaperAlarmItem, type: Type) {
when (type.ordinal) {
Type.SINGLE.ordinal -> {
if (wallpaperAlarmItem.setLock) startService(context, LockWallpaperService::class.java, WallpaperAction.START, ServiceConfig(wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.SINGLE.ordinal))
if (wallpaperAlarmItem.setHome) startService(context, HomeWallpaperService::class.java, WallpaperAction.START, ServiceConfig(wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.SINGLE.ordinal))
}
Type.LOCK.ordinal -> {
startService(context, LockWallpaperService::class.java, WallpaperAction.START, ServiceConfig(wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.LOCK.ordinal))
}
Type.HOME.ordinal -> {
startService(context, HomeWallpaperService::class.java, WallpaperAction.START, ServiceConfig(wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.HOME.ordinal))
}
}
}
/**
* Updates the wallpaper without changing the alarm
*/
private fun updateWallpaper(type: Type, setHome: Boolean, setLock: Boolean) {
when (type.ordinal) {
Type.SINGLE.ordinal -> {
if (setLock) startService(context, LockWallpaperService::class.java, WallpaperAction.UPDATE)
if (setHome) startService(context, HomeWallpaperService::class.java, WallpaperAction.UPDATE)
}
Type.LOCK.ordinal -> {
startService(context, LockWallpaperService::class.java, WallpaperAction.UPDATE)
}
Type.HOME.ordinal -> {
startService(context, HomeWallpaperService::class.java, WallpaperAction.UPDATE)
}
}
}
/**
* Cancels the alarm based on type
*/
private fun cancelAlarm(type: Type) {
Log.d(TAG, "Cancelling alarm for type: $type (requestCode: ${type.ordinal})")
val pendingIntent = PendingIntent.getBroadcast(
context,
type.ordinal,
@@ -320,25 +330,34 @@ class WallpaperAlarmSchedulerImpl @Inject constructor(
alarmManager.cancel(pendingIntent)
}
/**
* Starts the service to change the wallpaper
*/
private fun startService(
context: Context,
serviceClass: Class<*>,
action: WallpaperAction,
config: ServiceConfig? = null
) {
val serviceIntent = Intent(context, serviceClass).apply {
this.action = action::class.java.simpleName
config?.let {
it.homeInterval?.let { interval -> putExtra("homeInterval", interval) }
it.lockInterval?.let { interval -> putExtra("lockInterval", interval) }
it.scheduleSeparately?.let { separate -> putExtra("scheduleSeparately", separate) }
it.type?.let { type -> putExtra("type", type) }
}
}
context.startForegroundService(serviceIntent)
}
}
override fun updateWallpaperAlarm(wallpaperAlarmItem: WallpaperAlarmItem, firstLaunch: Boolean) {}
override fun updateWallpaper(scheduleSeparately: Boolean, setHome: Boolean, setLock: Boolean) {
if (scheduleSeparately) {
updateWallpaper(Type.LOCK, setHome, setLock)
updateWallpaper(Type.HOME, setHome, setLock)
} else {
updateWallpaper(Type.SINGLE, setHome, setLock)
}
}
private fun updateWallpaper(type: Type, setHome: Boolean, setLock: Boolean) {
when (type.ordinal) {
Type.SINGLE.ordinal -> {
if (setLock) startService(context, LockWallpaperService::class.java, WallpaperAction.UPDATE, null)
if (setHome) startService(context, HomeWallpaperService::class.java, WallpaperAction.UPDATE, null)
}
Type.LOCK.ordinal -> startService(context, LockWallpaperService::class.java, WallpaperAction.UPDATE, null)
Type.HOME.ordinal -> startService(context, HomeWallpaperService::class.java, WallpaperAction.UPDATE, null)
}
}
override fun cancelWallpaperAlarm(cancelLock: Boolean, cancelHome: Boolean) {
if (cancelLock) cancelAlarm(Type.LOCK)
if (cancelHome) cancelAlarm(Type.HOME)
if (cancelLock && cancelHome) {
cancelAlarm(Type.SINGLE)
cancelAlarm(Type.REFRESH)
}
}
}
@@ -35,7 +35,7 @@ class WallpaperBootAndChangeReceiver : BroadcastReceiver() {
Intent.ACTION_TIMEZONE_CHANGED,
ACTION_SHORTCUT -> {
saveExecutionTime(context)
val scheduler = WallpaperAlarmSchedulerImpl(context)
val scheduler = WallpaperAlarmSchedulerImpl(context, settingsDataStoreImpl)
val toggleChanger = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
val selectedAlbum = settingsDataStoreImpl.getString(SettingsConstants.HOME_ALBUM_NAME) ?: settingsDataStoreImpl.getString(SettingsConstants.LOCK_ALBUM_NAME) ?: ""
@@ -64,7 +64,7 @@ class WallpaperBootAndChangeReceiver : BroadcastReceiver() {
lockNextTime = settingsDataStoreImpl.getString(SettingsConstants.LOCK_NEXT_SET_TIME),
)
}
scheduler.scheduleRefresh(refresh)
WallpaperAlarmSchedulerImpl.scheduleRefresh(context, refresh)
}
}
}
@@ -3,6 +3,7 @@ package com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.core.SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
import com.anthonyla.paperize.core.Type
@@ -15,31 +16,34 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* Receiver for the alarm manager to change wallpaper
*/
@AndroidEntryPoint
class WallpaperReceiver : BroadcastReceiver() {
@Inject
lateinit var settingsDataStoreImpl: SettingsDataStore
lateinit var settingsDataStore: SettingsDataStore
companion object {
private const val TAG = "WallpaperReceiver"
}
override fun onReceive(context: Context?, intent: Intent?) {
if (context != null) {
val refresh = intent?.getBooleanExtra("refresh", false)
if (refresh == true) {
Log.d(TAG, "onReceive triggered.")
if (context != null && intent != null) {
val refresh = intent.getBooleanExtra("refresh", false)
if (refresh) {
val serviceIntent = Intent(context, HomeWallpaperService::class.java).apply {
action = HomeWallpaperService.Actions.REFRESH.toString()
}
context.startService(serviceIntent)
}
else {
val homeInterval = intent?.getIntExtra("homeInterval", WALLPAPER_CHANGE_INTERVAL_DEFAULT) ?: WALLPAPER_CHANGE_INTERVAL_DEFAULT
val lockInterval = intent?.getIntExtra("lockInterval", WALLPAPER_CHANGE_INTERVAL_DEFAULT) ?: WALLPAPER_CHANGE_INTERVAL_DEFAULT
val scheduleSeparately = intent?.getBooleanExtra("scheduleSeparately", false) ?: false
val type = intent?.getIntExtra("type", Type.SINGLE.ordinal) ?: Type.SINGLE.ordinal
val setHome = intent?.getBooleanExtra("setHome", false) ?: false
val setLock = intent?.getBooleanExtra("setLock", false) ?: false
val changeStartTime = intent?.getBooleanExtra("changeStartTime", false) ?: false
val startTime = intent?.getIntArrayExtra("startTime") ?: intArrayOf(0, 0)
context.startForegroundService(serviceIntent)
} else {
Log.d(TAG, "Regular wallpaper change alarm received.")
val homeInterval = intent.getIntExtra("homeInterval", WALLPAPER_CHANGE_INTERVAL_DEFAULT)
val lockInterval = intent.getIntExtra("lockInterval", WALLPAPER_CHANGE_INTERVAL_DEFAULT)
val scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
val type = intent.getIntExtra("type", Type.SINGLE.ordinal)
val setHome = intent.getBooleanExtra("setHome", false)
val setLock = intent.getBooleanExtra("setLock", false)
val changeStartTime = intent.getBooleanExtra("changeStartTime", false)
val startTime = intent.getIntArrayExtra("startTime") ?: intArrayOf(0, 0)
when (type) {
Type.SINGLE.ordinal -> {
@@ -54,29 +58,39 @@ class WallpaperReceiver : BroadcastReceiver() {
}
}
// Schedule next alarm for next wallpaper change
val origin = intent?.getIntExtra("origin", -1)?.takeIf { it != -1 }
val origin = intent.getIntExtra("origin", -1).takeIf { it != -1 }
Log.d(TAG, "Rescheduling next alarm from receiver with origin: $origin")
CoroutineScope(Dispatchers.IO).launch {
WallpaperAlarmSchedulerImpl(context).scheduleWallpaperAlarm(
wallpaperAlarmItem = WallpaperAlarmItem(
homeInterval = homeInterval,
lockInterval = lockInterval,
scheduleSeparately = scheduleSeparately,
setHome = setHome,
setLock = setLock,
changeStartTime = changeStartTime,
startTime = Pair(startTime[0], startTime[1]),
),
val homeNext = settingsDataStore.getString(SettingsConstants.HOME_NEXT_SET_TIME)
val lockNext = settingsDataStore.getString(SettingsConstants.LOCK_NEXT_SET_TIME)
val alarmItem = WallpaperAlarmItem(
homeInterval = homeInterval,
lockInterval = lockInterval,
scheduleSeparately = scheduleSeparately,
setHome = setHome,
setLock = setLock,
changeStartTime = changeStartTime,
startTime = Pair(startTime[0], startTime[1]),
)
val scheduler = WallpaperAlarmSchedulerImpl(context, settingsDataStore)
scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = alarmItem,
origin = origin,
homeNextTime = settingsDataStoreImpl.getString(SettingsConstants.HOME_NEXT_SET_TIME),
lockNextTime = settingsDataStoreImpl.getString(SettingsConstants.LOCK_NEXT_SET_TIME),
changeImmediate = false,
cancelImmediate = false,
setAlarm = true,
firstLaunch = false,
homeNextTime = homeNext,
lockNextTime = lockNext,
)
}
}
}
}
private fun startService(context: Context, serviceClass: Class<*>, action: String, homeInterval: Int? = null, lockInterval: Int? = null, scheduleSeparately: Boolean? = null, type: Int? = null) {
private fun startService(context: Context, serviceClass: Class<*>, action: String, homeInterval: Int?, lockInterval: Int?, scheduleSeparately: Boolean?, type: Int?) {
val serviceIntent = Intent(context, serviceClass).apply {
this.action = action
homeInterval?.let { putExtra("homeInterval", it) }
@@ -1,7 +1,6 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaper_service
import android.Manifest
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.app.WallpaperManager
@@ -17,45 +16,21 @@ import androidx.annotation.RequiresPermission
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.core.Type
import com.anthonyla.paperize.core.decompress
import com.anthonyla.paperize.core.findFirstValidUri
import com.anthonyla.paperize.core.getDeviceScreenSize
import com.anthonyla.paperize.core.getFolderMetadata
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.core.isDirectory
import com.anthonyla.paperize.core.isValidUri
import com.anthonyla.paperize.core.processBitmap
import com.anthonyla.paperize.core.retrieveBitmap
import com.anthonyla.paperize.core.*
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.anthonyla.paperize.feature.wallpaper.presentation.MainActivity
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState
import com.anthonyla.paperize.feature.wallpaper.tasker_shortcut.triggerWallpaperTaskerEvent
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperBootAndChangeReceiver
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import javax.inject.Inject
import kotlin.collections.containsKey
import kotlin.collections.shuffle
import kotlin.hashCode
import kotlin.text.contains
/**
* Service for changing home screen
*/
@AndroidEntryPoint
class HomeWallpaperService: Service() {
private val handleThread = HandlerThread("HomeThread")
@@ -74,21 +49,16 @@ class HomeWallpaperService: Service() {
REFRESH
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onBind(p0: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
handleThread.start()
workerHandler = Handler(handleThread.looper)
// Start foreground as soon as possible
if (!isForeground) {
val notification = createNotification(LocalDateTime.now())
if (notification != null) {
startForeground(1, notification)
isForeground = true
}
val notification = createInitialNotification()
startForeground(1, notification)
isForeground = true
}
}
@@ -102,12 +72,8 @@ class HomeWallpaperService: Service() {
type = intent.getIntExtra("type", Type.SINGLE.ordinal)
workerTaskStart()
}
Actions.UPDATE.toString() -> {
workerTaskUpdate()
}
Actions.REFRESH.toString() -> {
workerTaskRefresh()
}
Actions.UPDATE.toString() -> workerTaskUpdate()
Actions.REFRESH.toString() -> workerTaskRefresh()
}
}
return START_NOT_STICKY
@@ -124,7 +90,6 @@ class HomeWallpaperService: Service() {
delay(50)
changeWallpaper(this@HomeWallpaperService)
withContext(Dispatchers.Main) {
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
}
@@ -134,7 +99,6 @@ class HomeWallpaperService: Service() {
CoroutineScope(Dispatchers.Default).launch {
updateCurrentWallpaper(this@HomeWallpaperService)
withContext(Dispatchers.Main) {
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
}
@@ -144,44 +108,23 @@ class HomeWallpaperService: Service() {
CoroutineScope(Dispatchers.Default).launch {
refreshAlbum(this@HomeWallpaperService)
withContext(Dispatchers.Main) {
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
}
}
// Creates a notification for the wallpaper service
private fun createNotification(nextSetTime: LocalDateTime?): android.app.Notification? {
nextSetTime?.let {
val changeWallpaperIntent = Intent(this, WallpaperBootAndChangeReceiver::class.java).apply {
action = "com.anthonyla.paperize.SHORTCUT"
}
val pendingChangeWallpaperIntent = PendingIntent.getBroadcast(
this,
0,
changeWallpaperIntent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
val mainActivityIntent = Intent(this, MainActivity::class.java)
val pendingMainActivityIntent = PendingIntent.getActivity(
this,
3,
mainActivityIntent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val formattedNextSetTime = nextSetTime.format(formatter)
return NotificationCompat.Builder(this, "wallpaper_service_channel").apply {
setContentTitle(getString(R.string.app_name))
setContentText(getString(R.string.next_wallpaper_change, formattedNextSetTime))
setSmallIcon(R.drawable.notification_icon)
setContentIntent(pendingMainActivityIntent)
addAction(R.drawable.notification_icon, getString(R.string.change_wallpaper), pendingChangeWallpaperIntent)
priority = NotificationCompat.PRIORITY_DEFAULT
setAutoCancel(true)
}.build()
}
return null
private fun createInitialNotification(): android.app.Notification {
val mainActivityIntent = Intent(this, MainActivity::class.java)
val pendingMainActivityIntent = PendingIntent.getActivity(
this, 3, mainActivityIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
return NotificationCompat.Builder(this, "wallpaper_service_channel").apply {
setContentTitle(getString(R.string.app_name))
setContentText(getString(R.string.changing_wallpaper))
setSmallIcon(R.drawable.notification_icon)
setContentIntent(pendingMainActivityIntent)
priority = NotificationCompat.PRIORITY_DEFAULT
}.build()
}
private suspend fun getWallpaperSettings(): SettingsState.ServiceSettings {
@@ -209,10 +152,6 @@ class HomeWallpaperService: Service() {
)
}
/**
* Changes the wallpaper to the next wallpaper in the queue of the selected album
* If none left, reshuffle the wallpapers and pick the first one
*/
private suspend fun changeWallpaper(context: Context) {
try {
var selectedAlbum = albumRepository.getSelectedAlbums().first()
@@ -226,7 +165,6 @@ class HomeWallpaperService: Service() {
return
}
// Check if we should skip wallpaper change due to landscape orientation
if (settings.skipLandscape && context.resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE) {
Log.d("PaperizeWallpaperChanger", "Skipping wallpaper change - device is in landscape mode")
onDestroy()
@@ -239,7 +177,6 @@ class HomeWallpaperService: Service() {
return
}
when {
// Case: Set home and lock screen wallpapers using separate albums (home screen and lock screen album)
settings.setHome && settings.setLock && scheduleSeparately -> {
var wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull()
if (wallpaper == null) {
@@ -331,7 +268,6 @@ class HomeWallpaperService: Service() {
}
}
}
// Case: Set home and lock screen wallpapers using the same album (home screen album)
settings.setHome && settings.setLock && !scheduleSeparately -> {
var wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull()
if (wallpaper == null) {
@@ -421,7 +357,6 @@ class HomeWallpaperService: Service() {
}
}
}
// Case: Set home screen wallpaper (home screen album)
settings.setHome -> {
var wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull()
if (wallpaper == null) {
@@ -510,44 +445,12 @@ class HomeWallpaperService: Service() {
}
}
}
// Run notification
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val currentTime = LocalDateTime.now()
val homeNextSetTime: LocalDateTime = currentTime.plusMinutes(homeInterval.toLong())
val lockNextSetTime: LocalDateTime = try {
LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.LOCK_NEXT_SET_TIME))
} catch (e: Exception) {
currentTime
}
val nextSetTime: LocalDateTime = when {
homeInterval == lockInterval -> homeNextSetTime
settings.setHome && settings.setLock && scheduleSeparately -> {
if (homeNextSetTime.isBefore(lockNextSetTime) && homeNextSetTime.isAfter(currentTime)) {
homeNextSetTime
} else lockNextSetTime
}
else -> homeNextSetTime
}
nextSetTime.let {
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter))
settingsDataStoreImpl.putString(SettingsConstants.HOME_NEXT_SET_TIME, homeNextSetTime.toString())
settingsDataStoreImpl.putString(SettingsConstants.LOCK_NEXT_SET_TIME, lockNextSetTime.toString())
}
val notification = createNotification(nextSetTime)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notification?.let { notificationManager.notify(1, it) }
Log.d("HomeWallpaperService", "Wallpaper change task completed.")
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in changing wallpaper", e)
Log.e("PaperizeWallpaperChanger", "Error in changing wallpaper (Home)", e)
}
}
/**
* Updates the current wallpaper with current settings
*/
private suspend fun updateCurrentWallpaper(context: Context) {
try {
val selectedAlbum = albumRepository.getSelectedAlbums().first()
@@ -564,7 +467,6 @@ class HomeWallpaperService: Service() {
val currentHomeWallpaper = settingsDataStoreImpl.getString(SettingsConstants.CURRENT_HOME_WALLPAPER) ?: ""
val currentLockWallpaper = settingsDataStoreImpl.getString(SettingsConstants.CURRENT_LOCK_WALLPAPER) ?: ""
// Check if we're using the same wallpaper for both home and lock
val bothEnabled = settings.setHome && settings.setLock && currentHomeWallpaper == currentLockWallpaper
if (bothEnabled) {
@@ -583,7 +485,6 @@ class HomeWallpaperService: Service() {
both = true
)
} else {
// Update home screen only
if (settings.setHome) {
setWallpaper(
context = context,
@@ -605,9 +506,6 @@ class HomeWallpaperService: Service() {
}
}
/**
* Sets the wallpaper to the given uri
*/
private fun setWallpaper(
context: Context,
wallpaper: Uri?,
@@ -630,11 +528,9 @@ class HomeWallpaperService: Service() {
if (bitmap == null) return false
else if (wallpaperManager.isSetWallpaperAllowed) {
if (both) {
// Need to get settings to apply different effects for home and lock
CoroutineScope(Dispatchers.IO).launch {
val settings = getWallpaperSettings()
// Process bitmap for home screen with home settings
processBitmap(
size.width, size.height, bitmap,
settings.darken, settings.homeDarkenPercentage,
@@ -646,7 +542,6 @@ class HomeWallpaperService: Service() {
setWallpaperSafely(homeImage, WallpaperManager.FLAG_SYSTEM, wallpaperManager)
}
// Process bitmap for lock screen with lock settings
processBitmap(
size.width, size.height, bitmap,
settings.darken, settings.lockDarkenPercentage,
@@ -659,7 +554,6 @@ class HomeWallpaperService: Service() {
}
}
} else {
// Single wallpaper processing (existing logic)
processBitmap(size.width, size.height, bitmap, darken, darkenPercent, scaling, blur, blurPercent, vignette, vignettePercent, grayscale, grayscalePercent)?.let { image ->
setWallpaperSafely(image, WallpaperManager.FLAG_SYSTEM, wallpaperManager)
}
@@ -676,9 +570,6 @@ class HomeWallpaperService: Service() {
return false
}
/**
* Refreshes the album by deleting invalid wallpapers and updating folder cover uri and wallpapers uri.
*/
private fun refreshAlbum(context: Context) {
CoroutineScope(Dispatchers.IO).launch {
Log.d("PaperizeWallpaperChanger", "Refreshing albums")
@@ -687,7 +578,6 @@ class HomeWallpaperService: Service() {
val settings = getWallpaperSettings()
albumsToRefresh.forEach { albumWithDetails ->
// Filter out invalid URIs, preserving the original order.
val validStandaloneWallpapers = albumWithDetails.wallpapers
.filter { isValidUri(context, it.wallpaperUri) }
@@ -695,7 +585,6 @@ class HomeWallpaperService: Service() {
.mapNotNull { folder ->
try {
val metadata = getFolderMetadata(folder.folderUri, context)
// Only rescan a folder if it has been modified
if (metadata.lastModified != folder.dateModified) {
val wallpapersInDb = folder.wallpapers
.filter { isValidUri(context, it.wallpaperUri) }
@@ -703,7 +592,6 @@ class HomeWallpaperService: Service() {
val wallpapersOnDisk = getWallpaperFromFolder(folder.folderUri, context)
// Find new wallpapers not already in the DB for this folder
val newWallpapers = wallpapersOnDisk
.filterNot { wallpapersInDb.containsKey(it.wallpaperUri) }
.mapIndexed { index, wallpaper ->
@@ -724,15 +612,14 @@ class HomeWallpaperService: Service() {
folderName = metadata.filename
)
} else {
folder // Folder hasn't changed, return it as is
folder
}
} catch (e: Exception) {
Log.w("PaperizeWallpaperChanger", "Failed to process folder ${folder.folderUri}: ${e.message}")
null // Filter out this folder if it can't be processed
null
}
}
// Rest of the function remains the same...
val allValidWallpapers = (updatedFolders.flatMap { it.wallpapers } + validStandaloneWallpapers)
.sortedBy { it.order }
@@ -792,4 +679,4 @@ class HomeWallpaperService: Service() {
}
}
}
}
}
@@ -1,7 +1,6 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaper_service
import android.Manifest
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.app.WallpaperManager
@@ -17,36 +16,21 @@ import androidx.annotation.RequiresPermission
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.core.Type
import com.anthonyla.paperize.core.decompress
import com.anthonyla.paperize.core.getDeviceScreenSize
import com.anthonyla.paperize.core.isValidUri
import com.anthonyla.paperize.core.processBitmap
import com.anthonyla.paperize.core.retrieveBitmap
import com.anthonyla.paperize.core.*
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.anthonyla.paperize.feature.wallpaper.presentation.MainActivity
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState
import com.anthonyla.paperize.feature.wallpaper.tasker_shortcut.triggerWallpaperTaskerEvent
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperBootAndChangeReceiver
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import javax.inject.Inject
/**
* Service to change lock screen
*/
@AndroidEntryPoint
class LockWallpaperService: Service() {
private val handleThread = HandlerThread("LockThread")
@@ -64,21 +48,16 @@ class LockWallpaperService: Service() {
UPDATE
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onBind(p0: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
handleThread.start()
workerHandler = Handler(handleThread.looper)
// Start foreground as soon as possible
if (!isForeground) {
val notification = createNotification(LocalDateTime.now())
if (notification != null) {
startForeground(1, notification)
isForeground = true
}
val notification = createInitialNotification()
startForeground(1, notification)
isForeground = true
}
}
@@ -92,9 +71,7 @@ class LockWallpaperService: Service() {
type = intent.getIntExtra("type", Type.SINGLE.ordinal)
workerTaskStart()
}
Actions.UPDATE.toString() -> {
workerTaskUpdate()
}
Actions.UPDATE.toString() -> workerTaskUpdate()
}
}
return START_NOT_STICKY
@@ -107,65 +84,37 @@ class LockWallpaperService: Service() {
}
private fun workerTaskStart() {
workerHandler.post {
CoroutineScope(Dispatchers.Default).launch {
changeWallpaper(this@LockWallpaperService)
withContext(Dispatchers.Main) {
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
CoroutineScope(Dispatchers.Default).launch {
changeWallpaper(this@LockWallpaperService)
withContext(Dispatchers.Main) {
stopSelf()
}
}
}
private fun workerTaskUpdate() {
workerHandler.post {
CoroutineScope(Dispatchers.Default).launch {
updateCurrentWallpaper(this@LockWallpaperService)
withContext(Dispatchers.Main) {
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
CoroutineScope(Dispatchers.Default).launch {
updateCurrentWallpaper(this@LockWallpaperService)
withContext(Dispatchers.Main) {
stopSelf()
}
}
}
// Creates a notification for the wallpaper service
private fun createNotification(nextSetTime: LocalDateTime?): android.app.Notification? {
nextSetTime?.let {
val changeWallpaperIntent = Intent(this, WallpaperBootAndChangeReceiver::class.java)
val pendingChangeWallpaperIntent = PendingIntent.getBroadcast(
this,
0,
changeWallpaperIntent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
val mainActivityIntent = Intent(this, MainActivity::class.java)
val pendingMainActivityIntent = PendingIntent.getActivity(
this,
3,
mainActivityIntent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val formattedNextSetTime = nextSetTime.format(formatter)
// Build the notification
return NotificationCompat.Builder(this, "wallpaper_service_channel").apply {
setContentTitle(getString(R.string.app_name))
setContentText(getString(R.string.next_wallpaper_change, formattedNextSetTime))
setSmallIcon(R.drawable.notification_icon)
setContentIntent(pendingMainActivityIntent)
addAction(R.drawable.notification_icon, getString(R.string.change_wallpaper), pendingChangeWallpaperIntent)
priority = NotificationCompat.PRIORITY_DEFAULT
setAutoCancel(true)
}.build()
}
return null
private fun createInitialNotification(): android.app.Notification {
val mainActivityIntent = Intent(this, MainActivity::class.java)
val pendingMainActivityIntent = PendingIntent.getActivity(
this, 3, mainActivityIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
return NotificationCompat.Builder(this, "wallpaper_service_channel").apply {
setContentTitle(getString(R.string.app_name))
setContentText(getString(R.string.changing_wallpaper))
setSmallIcon(R.drawable.notification_icon)
setContentIntent(pendingMainActivityIntent)
priority = NotificationCompat.PRIORITY_DEFAULT
}.build()
}
private suspend fun getWallpaperSettings(): SettingsState.ServiceSettings {
return SettingsState.ServiceSettings(
enableChanger = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false,
@@ -191,10 +140,6 @@ class LockWallpaperService: Service() {
)
}
/**
* Changes the wallpaper to the next wallpaper in the queue of the selected album
* If none left, reshuffle the wallpapers and pick the first one
*/
private suspend fun changeWallpaper(context: Context) {
try {
val selectedAlbum = albumRepository.getSelectedAlbums().first()
@@ -208,7 +153,6 @@ class LockWallpaperService: Service() {
return
}
// Check if we should skip wallpaper change due to landscape orientation
if (settings.skipLandscape && context.resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE) {
Log.d("PaperizeWallpaperChanger", "Skipping wallpaper change - device is in landscape mode")
onDestroy()
@@ -222,7 +166,6 @@ class LockWallpaperService: Service() {
return
}
when {
// Case: Set home and lock screen wallpapers using separate albums (home screen and lock screen album)
settings.setHome && settings.setLock && scheduleSeparately -> {
var wallpaper = lockAlbum.album.lockWallpapersInQueue.firstOrNull()
if (wallpaper == null) {
@@ -307,9 +250,7 @@ class LockWallpaperService: Service() {
}
}
}
// Case: Set home and lock screen wallpapers using the same album (home screen album)
settings.setHome && settings.setLock && !scheduleSeparately -> { /* handled by home wallpaper service */ return }
// Case: Set lock screen wallpaper (lock screen album)
settings.setLock -> {
var wallpaper = lockAlbum.album.lockWallpapersInQueue.firstOrNull()
if (wallpaper == null) {
@@ -397,64 +338,12 @@ class LockWallpaperService: Service() {
}
}
}
// Run notification
if (homeInterval != lockInterval && scheduleSeparately) {
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val homeNextSetTime = try {
LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.HOME_NEXT_SET_TIME))
} catch (_: Exception) {
LocalDateTime.now()
}
val currentTime = LocalDateTime.now()
val lockNextSetTime = currentTime.plusMinutes(lockInterval.toLong())
val nextSetTime = when {
lockNextSetTime.isBefore(homeNextSetTime) && lockNextSetTime.isAfter(currentTime) -> lockNextSetTime
homeNextSetTime.isAfter(currentTime) -> homeNextSetTime
else -> lockNextSetTime
}
nextSetTime?.let {
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter))
settingsDataStoreImpl.putString(SettingsConstants.LOCK_NEXT_SET_TIME, lockNextSetTime.toString())
settingsDataStoreImpl.putString(SettingsConstants.HOME_NEXT_SET_TIME, homeNextSetTime.toString())
}
val notification = createNotification(nextSetTime)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notification?.let { notificationManager.notify(1, it) }
}
else if (settings.setLock && !settings.setHome && !scheduleSeparately) {
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val homeNextSetTime = try {
LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.HOME_NEXT_SET_TIME))
} catch (_: Exception) {
LocalDateTime.now()
}
val currentTime = LocalDateTime.now()
val lockNextSetTime = currentTime.plusMinutes(homeInterval.toLong())
val nextSetTime = when {
lockNextSetTime.isBefore(homeNextSetTime) && lockNextSetTime.isAfter(currentTime) -> lockNextSetTime
homeNextSetTime.isAfter(currentTime) -> homeNextSetTime
else -> lockNextSetTime
}
nextSetTime?.let {
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter))
settingsDataStoreImpl.putString(SettingsConstants.LOCK_NEXT_SET_TIME, lockNextSetTime.toString())
settingsDataStoreImpl.putString(SettingsConstants.HOME_NEXT_SET_TIME, homeNextSetTime.toString())
}
val notification = createNotification(nextSetTime)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notification?.let { notificationManager.notify(1, it) }
}
Log.d("LockWallpaperService", "Wallpaper change task completed.")
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in changing wallpaper", e)
Log.e("PaperizeWallpaperChanger", "Error in changing wallpaper (Lock)", e)
}
}
/**
* Updates the current wallpaper with current settings
*/
private suspend fun updateCurrentWallpaper(context: Context) {
try {
val selectedAlbum = albumRepository.getSelectedAlbums().first()
@@ -487,9 +376,6 @@ class LockWallpaperService: Service() {
}
}
/**
* Sets the wallpaper to the given uri
*/
private fun setWallpaper(
context: Context,
wallpaper: Uri?,
@@ -542,4 +428,4 @@ class LockWallpaperService: Service() {
}
}
}
}
}
+1
View File
@@ -192,4 +192,5 @@
<string name="make_the_colors_grayscale">Make the colors grayscale</string>
<string name="shuffle_the_wallpapers">Shuffle the wallpapers</string>
<string name="prevent_changing_during_landscape_mode">Prevent changing during landscape mode</string>
<string name="changing_wallpaper">Changing wallpaper…</string>
</resources>