Compare commits

..
15 Commits
Author SHA1 Message Date
Anthonyy232 68e94fe284 Updated metadata for FDroid release 2024-06-04 19:00:21 -07:00
Anthonyy232 265edf8f63 Enable auto restart for alarm manager when opening the app 2024-06-04 18:32:26 -07:00
Anthonyy232 322a10bf0c Fixed users adding empty folder 2024-06-04 14:51:18 -07:00
Anthonyy232 f6688c84ab Fix checking permission for schedule exact alarm on Android 14 2024-06-04 12:46:13 -07:00
Anthony La 62a5934220 Update README.md 2024-06-04 11:20:38 -07:00
Anthony La 64dedae516 Merge pull request #12 from Anthonyy232/fix-schedule
Migrate wallpaper changer functionality from foreground service to alarm manager
2024-06-04 11:10:26 -07:00
Anthonyy232 1ff2539574 Updated version code 2024-06-04 10:54:22 -07:00
Anthonyy232 219a4cdb52 Changed gradle to include debug symbols automatically 2024-06-04 10:51:42 -07:00
Anthonyy232 322e6907ab Updated gradle to 8.8
Fixed ImageDecoder error on API 26
2024-06-04 10:39:38 -07:00
Anthonyy232 c39527b3b5 Reduced delay for delaying album
Fixed an issue where DocumentFileCompat would cause a crash on API 26
Fixed an issue where a folder with no name or protected folders like Downloads folder would cause a crash
2024-06-02 22:49:03 -07:00
Anthonyy232 068f78f86c Fixed album wallpapers not being refreshed before changing wallpapers
Fixed album cover art not being refreshed
2024-06-02 16:09:17 -07:00
Anthonyy232 87ef7ebaf0 Fixed notifications showing wrong time 2024-06-02 12:43:46 -07:00
Anthonyy232 996208b03d Migrated wallpaper changer functionality to alarm manager-service approach to improve reliability for long intervals
Fixed navigation bug when resetting from settings or going from notifications page to home page navigating twice
2024-06-02 02:08:27 -07:00
Anthonyy232 ec54bbb8c5 Fixed navigation bug when going to home screen 2024-05-31 01:29:58 -07:00
Anthonyy232 b52a47770d Fixed album not deleting when it is empty 2024-05-27 18:48:38 -07:00
44 changed files with 1587 additions and 714 deletions

No files matched your search

+3 -1
View File
@@ -53,6 +53,7 @@ I would love some help translating the app! Help me out with that [here](https:/
- [Landscapist](https://github.com/skydoves/landscapist) - A Compose and KPP image loading library that streamlines Glide, Coil, and Fresco
- [Zoomable](https://github.com/usuiat/Zoomable) - A library that provides a zoomable and pannable view, which can be used with any view you want
- [AnimatedFABMenu](https://github.com/rajaumair7890/AnimatedFABMenu) - A animated floating action button with Material 3 design
- [DocumentFileCompat](https://github.com/ItzNotABug/DocumentFileCompat) - A DocumentFile wrapper that caches the result to improve efficiency
Thanks to the creators and maintainers of the open-source libraries used in this project.
@@ -63,7 +64,8 @@ This project is built using Kotlin, Java, and Gradle. Here are the steps to buil
### Prerequisites
- Java 8 (1.8)
- Android Studio Jellyfish | 2023.3.1 or later
- Gradle 8.4.1 or later
- Android Gradle Plugin 8.4.1 or later
- Gradle 8.8
- Minimum SDK 26
### Steps
+23 -20
View File
@@ -18,13 +18,16 @@ android {
applicationId = "com.anthonyla.paperize"
minSdk = 26
targetSdk = 34
versionCode = 15
versionName = "1.4.1"
versionCode = 19
versionName = "1.5.1"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary = true
}
ndk {
debugSymbolLevel = "FULL"
}
}
@@ -67,40 +70,40 @@ androidComponents {
dependencies {
implementation("androidx.core:core-ktx:1.13.1")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.1")
implementation("androidx.activity:activity-compose:1.9.0")
implementation(platform("androidx.compose:compose-bom:2024.05.00"))
implementation("androidx.compose.ui:ui:1.7.0-beta01")
implementation("androidx.compose.ui:ui-graphics:1.7.0-beta01")
implementation("androidx.compose.ui:ui-tooling-preview:1.7.0-beta01")
implementation("androidx.compose.material3:material3:1.3.0-beta01")
implementation("androidx.navigation:navigation-compose:2.8.0-beta01")
implementation("androidx.compose.material:material:1.7.0-beta01")
implementation("androidx.compose.ui:ui:1.7.0-beta02")
implementation("androidx.compose.ui:ui-graphics:1.7.0-beta02")
implementation("androidx.compose.ui:ui-tooling-preview:1.7.0-beta02")
implementation("androidx.compose.material3:material3:1.3.0-beta02")
implementation("androidx.navigation:navigation-compose:2.8.0-beta02")
implementation("androidx.compose.material:material:1.7.0-beta02")
implementation("androidx.datastore:datastore:1.1.1")
implementation("androidx.datastore:datastore-preferences:1.1.1")
implementation("androidx.compose.material:material-icons-extended:1.7.0-beta01")
implementation("androidx.compose.material:material-icons-extended:1.7.0-beta02")
implementation("com.google.accompanist:accompanist-adaptive:0.34.0")
implementation("androidx.hilt:hilt-navigation-compose:1.2.0")
implementation("androidx.compose.animation:animation:1.7.0-beta01")
implementation("androidx.compose.animation:animation:1.7.0-beta02")
implementation("androidx.core:core-splashscreen:1.2.0-alpha01")
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.0")
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.1")
implementation("com.google.code.gson:gson:2.11.0")
implementation("androidx.documentfile:documentfile:1.1.0-alpha01")
implementation("net.engawapg.lib:zoomable:1.7.0-beta02")
implementation("com.github.skydoves:landscapist-glide:2.3.3")
implementation("androidx.work:work-runtime-ktx:2.10.0-alpha02")
implementation("androidx.hilt:hilt-work:1.2.0")
implementation("com.airbnb.android:lottie-compose:6.4.0")
implementation("com.airbnb.android:lottie-compose:6.4.1")
implementation("com.google.accompanist:accompanist-permissions:0.35.0-alpha")
implementation("com.mikepenz:aboutlibraries-core:11.2.0")
implementation("com.mikepenz:aboutlibraries-compose-m3:11.2.0")
implementation("androidx.compose.foundation:foundation:1.7.0-beta01")
implementation("com.mikepenz:aboutlibraries-core:11.2.1")
implementation("com.mikepenz:aboutlibraries-compose-m3:11.2.1")
implementation("androidx.compose.foundation:foundation:1.7.0-beta02")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.6.0-beta01")
androidTestImplementation("androidx.compose.ui:ui-test-junit4:1.7.0-beta01")
debugImplementation("androidx.compose.ui:ui-tooling:1.7.0-beta01")
debugImplementation("androidx.compose.ui:ui-test-manifest:1.7.0-beta01")
androidTestImplementation("androidx.test.espresso:espresso-core:3.6.0-rc01")
androidTestImplementation("androidx.compose.ui:ui-test-junit4:1.7.0-beta02")
debugImplementation("androidx.compose.ui:ui-tooling:1.7.0-beta02")
debugImplementation("androidx.compose.ui:ui-test-manifest:1.7.0-beta02")
implementation("com.google.dagger:hilt-android:2.51.1")
ksp("com.google.dagger:hilt-android-compiler:2.51.1")
implementation("androidx.room:room-runtime:2.6.1")
+9 -10
View File
@@ -2,17 +2,12 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<queries>
<intent>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent>
</queries>
<application
android:allowBackup="true"
android:name=".App"
@@ -33,11 +28,15 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".feature.wallpaper.wallpaper_service.WallpaperService" android:foregroundServiceType="mediaPlayback"/>
<receiver android:name=".feature.wallpaper.wallpaper_service.WallpaperBootReceiver"
android:exported="true">
<receiver android:name=".feature.wallpaper.wallpaper_alarmmanager.WallpaperReceiver" />
<service android:name=".feature.wallpaper.wallpaper_service.WallpaperService1"/>
<service android:name=".feature.wallpaper.wallpaper_service.WallpaperService2"/>
<receiver android:name=".feature.wallpaper.wallpaper_alarmmanager.WallpaperBootAndTimeChangeReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
</intent-filter>
</receiver>
<provider
@@ -24,4 +24,6 @@ object SettingsConstants {
const val SCHEDULE_SEPARATELY = "schedule_separately"
const val BLUR = "blur"
const val BLUR_PERCENTAGE = "blur_percentage"
const val NEXT_SET_TIME_1 = "next_set_time_1"
const val NEXT_SET_TIME_2 = "next_set_time_2"
}
@@ -18,6 +18,8 @@ import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.google.android.renderscript.Toolkit
import com.lazygeniouz.dfc.file.DocumentFileCompat
enum class Type { HOME, LOCK, BOTH }
/**
* Get the dimensions of the image from the uri
*/
@@ -147,12 +149,18 @@ fun blurBitmap(source: Bitmap, percent: Int): Bitmap {
* Retrieve wallpaper URIs from a folder directory URI
*/
fun getWallpaperFromFolder(folderUri: String, context: Context): List<String> {
val folderDocumentFile = DocumentFileCompat.fromTreeUri(context, folderUri.toUri())
return listFilesRecursive(folderDocumentFile, context)
try {
val folderDocumentFile = DocumentFileCompat.fromTreeUri(context, folderUri.toUri())
return listFilesRecursive(folderDocumentFile, context)
} catch (e: Exception) {
val folderDocumentFile = DocumentFile.fromTreeUri(context, folderUri.toUri())
return listFilesRecursive(folderDocumentFile, context)
}
}
/**
* Helper function to recursively list files in a directory
* Helper function to recursively list files in a directory for DocumentFileCompat
*/
fun listFilesRecursive(parent: DocumentFileCompat?, context: Context): List<String> {
val files = mutableListOf<String>()
@@ -168,6 +176,21 @@ fun listFilesRecursive(parent: DocumentFileCompat?, context: Context): List<Stri
}
return files
}
/** Overloaded version of the function for DocumentFile */
fun listFilesRecursive(parent: DocumentFile?, context: Context): List<String> {
val files = mutableListOf<String>()
parent?.listFiles()?.forEach { file ->
if (file.isDirectory) {
files.addAll(listFilesRecursive(file, context))
} else {
val allowedExtensions = listOf("jpg", "jpeg", "png", "heif", "webp", "JPG", "JPEG", "PNG", "HEIF", "WEBP")
if ((file.name?.substringAfterLast(".") ?: "") in allowedExtensions) {
files.add(file.uri.toString())
}
}
}
return files
}
/**
* Helper function to find the first valid URI from a list of wallpapers
@@ -191,3 +214,28 @@ fun findFirstValidUri(context: Context, wallpapers: List<Wallpaper>, folders: Li
return null
}
/**
* Get the folder name from the folder URI
*/
fun getFolderNameFromUri(folderUri: String, context: Context): String? {
return try {
DocumentFileCompat.fromTreeUri(context, folderUri.toUri())?.name
} catch (e: Exception) {
DocumentFile.fromTreeUri(context, folderUri.toUri())?.name
}
}
/**
* Check if a URI is valid
*/
fun isValidUri(context: Context, uriString: String?): Boolean {
val uri = uriString?.toUri()
return try {
uri?.let {
val inputStream = context.contentResolver.openInputStream(it)
inputStream?.close()
}
true
} catch (e: Exception) { false }
}
@@ -3,12 +3,14 @@ package com.anthonyla.paperize.feature.wallpaper.presentation
import android.Manifest
import android.animation.ObjectAnimator
import android.app.Activity
import android.app.ActivityManager
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.view.animation.AccelerateInterpolator
import androidx.activity.ComponentActivity
@@ -29,6 +31,7 @@ import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
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.album.AlbumsEvent
import com.anthonyla.paperize.feature.wallpaper.presentation.album.AlbumsViewModel
@@ -37,12 +40,12 @@ import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.Set
import com.anthonyla.paperize.feature.wallpaper.presentation.themes.PaperizeTheme
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.WallpaperEvent
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.WallpaperScreenViewModel
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.WallpaperService
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAlarmItem
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperReceiver
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperScheduler
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import javax.inject.Inject
@@ -78,10 +81,9 @@ class MainActivity : ComponentActivity() {
splashScreen.setKeepOnScreenCondition { settingsViewModel.setKeepOnScreenCondition }
setContent {
val scheduler = WallpaperScheduler(context)
val settingsState = settingsViewModel.state.collectAsStateWithLifecycle()
val selectedState = wallpaperScreenViewModel.state.collectAsStateWithLifecycle()
val isFirstLaunch = runBlocking { settingsDataStoreImpl.getBoolean(SettingsConstants.FIRST_LAUNCH) } ?: true
if (isFirstLaunch) {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
settingsViewModel.onEvent(SettingsEvent.Reset)
@@ -92,40 +94,44 @@ class MainActivity : ComponentActivity() {
contentResolver.releasePersistableUriPermission(permission.uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
}
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
LifecycleEventEffect(Lifecycle.Event.ON_CREATE) {
lifecycleScope.launch {
val serviceIntent = Intent(this@MainActivity, WallpaperService::class.java)
val isAlreadyRunning = withContext(Dispatchers.IO) {
val activityManager = getSystemService(ACTIVITY_SERVICE) as? ActivityManager
activityManager?.getRunningServices(Integer.MAX_VALUE)?.any {
it.service == serviceIntent.component
} ?: false
}
if (selectedState.value.selectedAlbum != null && settingsState.value.enableChanger) {
if (!isAlreadyRunning) {
settingsViewModel.onEvent(SettingsEvent.RefreshNextSetTime)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes1", settingsState.value.homeInterval)
putExtra("timeInMinutes2", settingsState.value.lockInterval)
putExtra("scheduleSeparately", settingsState.value.scheduleSeparately)
}
context.startForegroundService(intent)
if (settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) == true) {
val shouldScheduleSeparately = settingsDataStoreImpl.getBoolean(SettingsConstants.SCHEDULE_SEPARATELY) ?: false
val shouldScheduleAlarm = if (shouldScheduleSeparately) {
!(isPendingIntentSet(Type.HOME.ordinal) && isPendingIntentSet(Type.LOCK.ordinal))
} else {
!isPendingIntentSet(Type.BOTH.ordinal)
}
} else {
if (isAlreadyRunning) {
Intent(context, WallpaperService::class.java).also {
it.action = WallpaperService.Actions.STOP.toString()
context.startForegroundService(it)
}
if (shouldScheduleAlarm) {
scheduler.scheduleWallpaperAlarm(
WallpaperAlarmItem(
timeInMinutes1 = settingsDataStoreImpl.getInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
timeInMinutes2 = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
scheduleSeparately = shouldScheduleSeparately
), null, true, true
)
}
}
}
}
PaperizeTheme(settingsState.value.darkMode, settingsState.value.dynamicTheming) {
Surface(tonalElevation = 5.dp) {
PaperizeApp(isFirstLaunch, topInset)
PaperizeApp(isFirstLaunch, scheduler, topInset)
}
}
}
}
override fun onResume() {
super.onResume()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val alarmManager = ContextCompat.getSystemService(context, AlarmManager::class.java)
if (alarmManager?.canScheduleExactAlarms() == false) {
Intent().also { intent ->
intent.action = Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM
context.startActivity(intent)
}
}
}
@@ -136,4 +142,15 @@ class MainActivity : ComponentActivity() {
super.onAttachedToWindow()
topInset = window.decorView.rootWindowInsets.stableInsetTop.dp
}
private fun isPendingIntentSet(requestCode: Int): Boolean {
val intent = Intent(context.applicationContext, WallpaperReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
context.applicationContext,
requestCode,
intent,
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_NO_CREATE
)
return pendingIntent != null
}
}
@@ -56,7 +56,8 @@ import com.anthonyla.paperize.feature.wallpaper.util.navigation.Startup
import com.anthonyla.paperize.feature.wallpaper.util.navigation.WallpaperView
import com.anthonyla.paperize.feature.wallpaper.util.navigation.sharedXTransitionIn
import com.anthonyla.paperize.feature.wallpaper.util.navigation.sharedXTransitionOut
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.WallpaperService
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAlarmItem
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperScheduler
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
@@ -70,6 +71,7 @@ import java.nio.charset.StandardCharsets
@Composable
fun PaperizeApp(
firstLaunch: Boolean,
scheduler : WallpaperScheduler,
topInsets: Dp,
albumsViewModel: AlbumsViewModel = hiltViewModel(),
settingsViewModel: SettingsViewModel = hiltViewModel(),
@@ -92,12 +94,14 @@ fun PaperizeApp(
albumsViewModel.onEvent(AlbumsEvent.InitializeAlbum(albumWithWallpapers))
} else if (albumWithWallpapers.wallpapers.isEmpty() && albumWithWallpapers.folders.isEmpty() && albumWithWallpapers.album.initialized) {
if (navController.currentDestination?.route == Home::class.simpleName) {
navController.popBackStack<Home>(inclusive = false)
try {
navController.popBackStack<Home>(inclusive = false)
} catch (e: Exception) {
navController.navigate(Home)
}
}
albumsViewModel.onEvent(
AlbumsEvent.DeleteAlbumWithWallpapers(
albumWithWallpapers
)
AlbumsEvent.DeleteAlbumWithWallpapers(albumWithWallpapers)
)
}
}
@@ -118,10 +122,18 @@ fun PaperizeApp(
val wallpapersUri = wallpapers.map { it.wallpaperUri }.toSet()
val newSelectedAlbum = SelectedAlbum(
album = foundAlbum.album.copy(
homeWallpapersInQueue = selectedAlbum.album.homeWallpapersInQueue.filter { it in wallpapersUri },
lockWallpapersInQueue = selectedAlbum.album.lockWallpapersInQueue.filter { it in wallpapersUri },
currentHomeWallpaper = selectedAlbum.album.currentHomeWallpaper,
currentLockWallpaper = selectedAlbum.album.currentLockWallpaper,
homeWallpapersInQueue = if (selectedAlbum.album.homeWallpapersInQueue.firstOrNull() in wallpapersUri) {
val firstElement = selectedAlbum.album.homeWallpapersInQueue.first()
val modifiedWallpapersUri = wallpapersUri.filter { it != firstElement }
listOf(firstElement) + modifiedWallpapersUri.shuffled()
} else { wallpapersUri.shuffled() },
lockWallpapersInQueue = if (selectedAlbum.album.lockWallpapersInQueue.firstOrNull() in wallpapersUri) {
val firstElement = selectedAlbum.album.lockWallpapersInQueue.first()
val modifiedWallpapersUri = wallpapersUri.filter { it != firstElement }
listOf(firstElement) + modifiedWallpapersUri.shuffled()
} else { wallpapersUri.shuffled() },
currentHomeWallpaper = if (selectedAlbum.album.currentHomeWallpaper in wallpapersUri) selectedAlbum.album.currentHomeWallpaper else selectedAlbum.album.homeWallpapersInQueue.firstOrNull { it in wallpapersUri },
currentLockWallpaper = if (selectedAlbum.album.currentLockWallpaper in wallpapersUri) selectedAlbum.album.currentLockWallpaper else selectedAlbum.album.lockWallpapersInQueue.firstOrNull { it in wallpapersUri }
),
wallpapers = wallpapers
)
@@ -134,10 +146,7 @@ fun PaperizeApp(
)
} ?: run {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
Intent(context, WallpaperService::class.java).also {
it.action = WallpaperService.Actions.STOP.toString()
context.startForegroundService(it)
}
scheduler.cancelWallpaperAlarm()
}
}
}
@@ -175,9 +184,6 @@ fun PaperizeApp(
onAgree = {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
settingsViewModel.onEvent(SettingsEvent.SetFirstLaunch)
navController.navigate(Home) {
popUpTo<Startup> { inclusive = true }
}
}
else { navController.navigate(Notification) }
}
@@ -207,12 +213,7 @@ fun PaperizeApp(
}
) {
NotificationScreen(
onAgree = {
settingsViewModel.onEvent(SettingsEvent.SetFirstLaunch)
navController.navigate(Home) {
popUpTo<Notification> { inclusive = true }
}
}
onAgree = { settingsViewModel.onEvent(SettingsEvent.SetFirstLaunch) }
)
}
// Navigate to the home screen to view all albums and wallpapers
@@ -251,13 +252,12 @@ fun PaperizeApp(
if (settingsState.value.enableChanger) {
job?.cancel()
job = scope.launch {
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes1", timeInMinutes)
putExtra("timeInMinutes2", settingsState.value.lockInterval)
putExtra("scheduleSeparately", settingsState.value.scheduleSeparately)
}
context.startForegroundService(intent)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = timeInMinutes,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = settingsState.value.scheduleSeparately
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
}
}
},
@@ -266,13 +266,12 @@ fun PaperizeApp(
if (settingsState.value.enableChanger) {
job?.cancel()
job = scope.launch {
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes1", settingsState.value.homeInterval)
putExtra("timeInMinutes2", timeInMinutes)
putExtra("scheduleSeparately", settingsState.value.scheduleSeparately)
}
context.startForegroundService(intent)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = timeInMinutes,
scheduleSeparately = settingsState.value.scheduleSeparately
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
}
}
},
@@ -282,13 +281,12 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(3000)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.REQUEUE.toString()
putExtra("timeInMinutes1", timeInMinutes)
putExtra("timeInMinutes2", settingsState.value.lockInterval)
putExtra("scheduleSeparately", settingsState.value.scheduleSeparately)
}
context.startForegroundService(intent)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = timeInMinutes,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = settingsState.value.scheduleSeparately
)
alarmItem.let{scheduler.updateWallpaperAlarm(it)}
}
}
@@ -299,13 +297,12 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(3000)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.REQUEUE.toString()
putExtra("timeInMinutes1", settingsState.value.homeInterval)
putExtra("timeInMinutes2", timeInMinutes)
putExtra("scheduleSeparately", settingsState.value.scheduleSeparately)
}
context.startForegroundService(intent)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = timeInMinutes,
scheduleSeparately = settingsState.value.scheduleSeparately
)
alarmItem.let{scheduler.updateWallpaperAlarm(it)}
}
}
@@ -314,10 +311,7 @@ fun PaperizeApp(
if (selectedState.value.selectedAlbum != null) {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(false))
Intent(context, WallpaperService::class.java).also {
it.action = WallpaperService.Actions.STOP.toString()
context.startForegroundService(it)
}
scheduler.cancelWallpaperAlarm()
}
},
animate = settingsState.value.animate,
@@ -341,21 +335,15 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(2000)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes1", settingsState.value.homeInterval)
putExtra("timeInMinutes2", settingsState.value.lockInterval)
putExtra("scheduleSeparately", settingsState.value.scheduleSeparately)
}
context.startForegroundService(intent)
}
}
else {
Intent(context, WallpaperService::class.java).also {
it.action = WallpaperService.Actions.STOP.toString()
context.startForegroundService(it)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = settingsState.value.scheduleSeparately
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
}
}
else { scheduler.cancelWallpaperAlarm() }
},
onSelectAlbum = {album ->
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(true))
@@ -365,13 +353,12 @@ fun PaperizeApp(
}
job?.cancel()
job = scope.launch {
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes1", settingsState.value.homeInterval)
putExtra("timeInMinutes2", settingsState.value.lockInterval)
putExtra("scheduleSeparately", settingsState.value.scheduleSeparately)
}
context.startForegroundService(intent)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = settingsState.value.scheduleSeparately
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
}
},
onDarkenPercentage = {
@@ -380,10 +367,7 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(2000)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.UPDATE.toString()
}
context.startForegroundService(intent)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
}
}
},
@@ -393,10 +377,7 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(2000)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.UPDATE.toString()
}
context.startForegroundService(intent)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
}
}
},
@@ -408,10 +389,7 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(2000)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.UPDATE.toString()
}
context.startForegroundService(intent)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
}
}
}
@@ -423,33 +401,26 @@ fun PaperizeApp(
selectedState.value.selectedAlbum?.let {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
}
Intent(context, WallpaperService::class.java).also {
it.action = WallpaperService.Actions.STOP.toString()
context.startForegroundService(it)
}
scheduler.cancelWallpaperAlarm()
}
else if (selectedState.value.selectedAlbum!= null && (enableHome && !settingsState.value.setLockWallpaper) || (!enableHome && settingsState.value.setLockWallpaper)) {
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(false))
job?.cancel()
job = scope.launch {
delay(2000)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes1", settingsState.value.homeInterval)
putExtra("timeInMinutes2", settingsState.value.lockInterval)
putExtra("scheduleSeparately", false)
}
context.startForegroundService(intent)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = false
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
}
}
else if (selectedState.value.selectedAlbum != null && settingsState.value.enableChanger) {
job?.cancel()
job = scope.launch {
delay(2000)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.UPDATE.toString()
}
context.startForegroundService(intent)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
}
}
},
@@ -460,49 +431,40 @@ fun PaperizeApp(
selectedState.value.selectedAlbum?.let {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
}
Intent(context, WallpaperService::class.java).also {
it.action = WallpaperService.Actions.STOP.toString()
context.startForegroundService(it)
}
scheduler.cancelWallpaperAlarm()
}
else if (selectedState.value.selectedAlbum!= null && (enableLock && !settingsState.value.setHomeWallpaper) || (!enableLock && settingsState.value.setHomeWallpaper)) {
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(false))
job?.cancel()
job = scope.launch {
delay(2000)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes1", settingsState.value.homeInterval)
putExtra("timeInMinutes2", settingsState.value.lockInterval)
putExtra("scheduleSeparately", false)
}
context.startForegroundService(intent)
}
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = false
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}}
}
else if (selectedState.value.selectedAlbum != null && settingsState.value.enableChanger) {
job?.cancel()
job = scope.launch {
delay(2000)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.UPDATE.toString()
}
context.startForegroundService(intent)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
}
}
},
onScheduleSeparatelyChange = {
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(it))
onScheduleSeparatelyChange = { changeSeparately ->
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(changeSeparately))
if (selectedState.value.selectedAlbum!= null && settingsState.value.enableChanger) {
job?.cancel()
job = scope.launch {
delay(2000)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes1", settingsState.value.homeInterval)
putExtra("timeInMinutes2", settingsState.value.lockInterval)
putExtra("scheduleSeparately", it)
}
context.startForegroundService(intent)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = changeSeparately
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
}
}
},
@@ -512,10 +474,7 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(2000)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.UPDATE.toString()
}
context.startForegroundService(intent)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
}
}
},
@@ -525,10 +484,7 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(2000)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.UPDATE.toString()
}
context.startForegroundService(intent)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
}
}
},
@@ -567,7 +523,7 @@ fun PaperizeApp(
},
onShowFolderView = { folderName, wallpapers ->
val encodedWallpapers = runBlocking { encodeUri(uri = Gson().toJson(wallpapers)) }
navController.navigate("${NavScreens.FolderView.route}/$folderName/$encodedWallpapers")
navController.navigate("${NavScreens.FolderView.route}/${folderName ?: " "}/$encodedWallpapers")
}
)
}
@@ -679,7 +635,7 @@ fun PaperizeApp(
},
onShowFolderView = { folderName, wallpapers ->
val encodedWallpapers = runBlocking { encodeUri(uri = Gson().toJson(wallpapers)) }
navController.navigate("${NavScreens.FolderView.route}/$folderName/$encodedWallpapers")
navController.navigate("${NavScreens.FolderView.route}/${folderName ?: " "}/$encodedWallpapers")
},
onDeleteAlbum = {
navController.navigateUp()
@@ -737,17 +693,11 @@ fun PaperizeApp(
navController.navigate(Licenses)
},
onResetClick = {
navController.navigate(Startup) {
popUpTo<Settings> { inclusive = true }
}
settingsViewModel.onEvent(SettingsEvent.Reset)
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
albumsViewModel.onEvent(AlbumsEvent.Reset)
addAlbumViewModel.onEvent(AddAlbumEvent.Reset)
Intent(context, WallpaperService::class.java).also {
it.action = WallpaperService.Actions.STOP.toString()
context.startForegroundService(it)
}
scheduler.cancelWallpaperAlarm()
val contentResolver = context.contentResolver
val persistedUris = contentResolver.persistedUriPermissions
for (permission in persistedUris) {
@@ -188,7 +188,7 @@ fun AddAlbumScreen(
)
},
onFolderViewClick = {
onShowFolderView(folder.folderName, folder.wallpapers)
if (folder.wallpapers.isNotEmpty()) onShowFolderView(folder.folderName, folder.wallpapers)
},
modifier = Modifier.padding(4.dp).animateItem(
placementSpec = tween(
@@ -3,15 +3,15 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen
import android.app.Application
import android.content.Context
import androidx.core.net.toUri
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.getFolderNameFromUri
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.lazygeniouz.dfc.file.DocumentFileCompat
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
@@ -140,6 +140,7 @@ class AddAlbumViewModel @Inject constructor(
viewModelScope.launch {
if (event.directoryUri !in _state.value.folders.map { it.folderUri }) {
val wallpapers: List<String> = getWallpaperFromFolder(event.directoryUri, context)
if (wallpapers.isEmpty()) { return@launch }
val folderName = getFolderNameFromUri(event.directoryUri, context)
_state.update {
it.copy(
@@ -256,28 +257,4 @@ class AddAlbumViewModel @Inject constructor(
}
}
}
private fun getWallpaperFromFolder(folderUri: String, context: Context): List<String> {
val folderDocumentFile = DocumentFileCompat.fromTreeUri(context, folderUri.toUri())
return listFilesRecursive(folderDocumentFile, context)
}
private fun listFilesRecursive(parent: DocumentFileCompat?, context: Context): List<String> {
val files = mutableListOf<String>()
parent?.listFiles()?.forEach { file ->
if (file.isDirectory()) {
files.addAll(listFilesRecursive(file, context))
} else {
val allowedExtensions = listOf("jpg", "jpeg", "png", "heif", "webp", "JPG", "JPEG", "PNG", "HEIF", "WEBP")
if (file.extension in allowedExtensions) {
files.add(file.uri.toString())
}
}
}
return files
}
private fun getFolderNameFromUri(folderUri: String, context: Context): String? {
return DocumentFileCompat.fromTreeUri(context, folderUri.toUri())?.name
}
}
@@ -8,8 +8,6 @@ import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.findFirstValidUri
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.lazygeniouz.dfc.file.DocumentFileCompat
import dagger.hilt.android.lifecycle.HiltViewModel
@@ -95,27 +93,46 @@ class AlbumsViewModel @Inject constructor (
repository.deleteWallpaperList(invalidWallpapers)
}
// Update folder cover uri and children uri
// Update folder cover uri and wallpapers uri
albumWithWallpaper.folders.forEach { folder ->
DocumentFileCompat.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory ->
if (!folderDirectory.isDirectory()) {
repository.deleteFolder(folder)
} else {
val wallpapers = getWallpaperFromFolder(folder.folderUri, context)
val folderCoverFile = folder.coverUri?.let { DocumentFile.fromSingleUri(context, it.toUri()) }
val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull()
repository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers))
try {
DocumentFileCompat.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory ->
if (!folderDirectory.isDirectory()) {
repository.deleteFolder(folder)
} else {
val wallpapers = getWallpaperFromFolder(folder.folderUri, context)
val folderCoverFile = folder.coverUri?.let { DocumentFile.fromSingleUri(context, it.toUri()) }
val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull()
repository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers))
}
}
} catch (e: Exception) {
DocumentFile.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory ->
if (!folderDirectory.isDirectory) {
repository.deleteFolder(folder)
} else {
val wallpapers = getWallpaperFromFolder(folder.folderUri, context)
val folderCoverFile = folder.coverUri?.let { DocumentFile.fromSingleUri(context, it.toUri()) }
val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull()
repository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers))
}
}
}
}
}
albumWithWallpapers = repository.getAlbumsWithWallpaperAndFolder().first()
albumWithWallpapers.forEach { albumWithWallpaper ->
// Update album cover uri if null or invalid
val albumCoverFile = albumWithWallpaper.album.coverUri?.toUri()?.let { DocumentFile.fromSingleUri(context, it) }
if (albumCoverFile == null || !albumCoverFile.exists()) {
val newCoverUri = findFirstValidUri(context, albumWithWallpaper.wallpapers, albumWithWallpaper.folders)
repository.updateAlbum(albumWithWallpaper.album.copy(coverUri = newCoverUri))
// Delete empty albums
if (albumWithWallpaper.wallpapers.isEmpty() && albumWithWallpaper.folders.all { it.wallpapers.isEmpty() }) {
repository.deleteAlbum(albumWithWallpaper.album)
}
else {
// Update album cover uri if null or invalid
val albumCoverFile = albumWithWallpaper.album.coverUri?.toUri()?.let { DocumentFile.fromSingleUri(context, it) }
if (albumCoverFile == null || !albumCoverFile.exists()) {
val newCoverUri = findFirstValidUri(context, albumWithWallpaper.wallpapers, albumWithWallpaper.folders)
repository.updateAlbum(albumWithWallpaper.album.copy(coverUri = newCoverUri))
}
}
}
}
@@ -180,7 +180,7 @@ fun AlbumViewScreen(
)
},
onFolderViewClick = {
onShowFolderView(folder.folderName, folder.wallpapers)
if (folder.wallpapers.isNotEmpty()) onShowFolderView(folder.folderName, folder.wallpapers)
},
modifier = Modifier.padding(4.dp).animateItem(
placementSpec = tween(
@@ -208,7 +208,7 @@ fun AlbumViewScreen(
)
},
onFolderViewClick = {
onShowFolderView(folder.folderName, folder.wallpapers)
if (folder.wallpapers.isNotEmpty()) onShowFolderView(folder.folderName, folder.wallpapers)
},
modifier = Modifier.padding(4.dp),
animate = false
@@ -3,13 +3,13 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen
import android.app.Application
import android.content.Context
import androidx.core.net.toUri
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.getFolderNameFromUri
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.lazygeniouz.dfc.file.DocumentFileCompat
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
@@ -189,6 +189,7 @@ class AlbumViewScreenViewModel @Inject constructor(
viewModelScope.launch {
if (event.directoryUri !in event.album.folders.map { it.folderUri }) {
val wallpapers: List<String> = getWallpaperFromFolder(event.directoryUri, context)
if (wallpapers.isEmpty()) { return@launch }
val folderName = getFolderNameFromUri(event.directoryUri, context)
repository.upsertFolder(
Folder(
@@ -215,27 +216,4 @@ class AlbumViewScreenViewModel @Inject constructor(
}
}
private fun getWallpaperFromFolder(folderUri: String, context: Context): List<String> {
val folderDocumentFile = DocumentFileCompat.fromTreeUri(context, folderUri.toUri())
return listFilesRecursive(folderDocumentFile, context)
}
private fun listFilesRecursive(parent: DocumentFileCompat?, context: Context): List<String> {
val files = mutableListOf<String>()
parent?.listFiles()?.forEach { file ->
if (file.isDirectory()) {
files.addAll(listFilesRecursive(file, context))
} else {
val allowedExtensions = listOf("jpg", "jpeg", "png", "heif", "webp", "JPG", "JPEG", "PNG", "HEIF", "WEBP")
if (file.extension in allowedExtensions) {
files.add(file.uri.toString())
}
}
}
return files
}
private fun getFolderNameFromUri(folderUri: String, context: Context): String? {
return DocumentFileCompat.fromTreeUri(context, folderUri.toUri())?.name
}
}
@@ -183,34 +183,6 @@ class SettingsViewModel @Inject constructor (
}
}
is SettingsEvent.SetHomeWallpaperInterval -> {
viewModelScope.launch(Dispatchers.IO) {
settingsDataStoreImpl.putInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL, event.interval)
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val currentTime = LocalDateTime.now()
val nextSetTime: String?
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
if (_state.value.scheduleSeparately) {
val nextSetTime1 = currentTime.plusMinutes(event.interval.toLong())
val nextSetTime2 = currentTime.plusMinutes(_state.value.lockInterval.toLong())
nextSetTime = (if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2)!!.format(formatter)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, nextSetTime)
}
else {
nextSetTime = currentTime.plusMinutes(event.interval.toLong()).format(formatter)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, nextSetTime)
}
_state.update {
it.copy(
homeInterval = event.interval,
lastSetTime = currentTime.format(formatter),
nextSetTime = nextSetTime
)
}
}
}
is SettingsEvent.SetFirstSet -> {
viewModelScope.launch(Dispatchers.IO) {
settingsDataStoreImpl.putBoolean(SettingsConstants.FIRST_SET, false)
@@ -222,10 +194,40 @@ class SettingsViewModel @Inject constructor (
}
}
is SettingsEvent.SetHomeWallpaperInterval -> {
viewModelScope.launch(Dispatchers.IO) {
settingsDataStoreImpl.putInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL, event.interval)
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val currentTime = LocalDateTime.now()
val nextSetTime: String?
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
if (_state.value.scheduleSeparately) {
val nextSetTime1 = currentTime.plusMinutes(event.interval.toLong())
val nextSetTime2 = currentTime.plusMinutes(_state.value.lockInterval.toLong())
nextSetTime = (if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2)!!.format(formatter)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, nextSetTime)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_1, nextSetTime1.toString())
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_2, nextSetTime2.toString())
}
else {
nextSetTime = currentTime.plusMinutes(event.interval.toLong()).format(formatter)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, nextSetTime)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_1, currentTime.plusMinutes(event.interval.toLong()).toString())
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_2, currentTime.plusMinutes(event.interval.toLong()).toString())
}
_state.update {
it.copy(
homeInterval = event.interval,
lastSetTime = currentTime.format(formatter),
nextSetTime = nextSetTime
)
}
}
}
is SettingsEvent.SetLockWallpaperInterval -> {
viewModelScope.launch(Dispatchers.IO) {
settingsDataStoreImpl.putInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL, event.interval)
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val currentTime = LocalDateTime.now()
val nextSetTime: String?
@@ -235,10 +237,14 @@ class SettingsViewModel @Inject constructor (
val nextSetTime2 = currentTime.plusMinutes(event.interval.toLong())
nextSetTime = (if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2)!!.format(formatter)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, nextSetTime)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_1, nextSetTime1.toString())
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_2, nextSetTime2.toString())
}
else {
nextSetTime = currentTime.plusMinutes(event.interval.toLong()).format(formatter)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, nextSetTime)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_1, currentTime.plusMinutes(event.interval.toLong()).toString())
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_2, currentTime.plusMinutes(event.interval.toLong()).toString())
}
_state.update {
it.copy(
@@ -380,6 +386,8 @@ class SettingsViewModel @Inject constructor (
settingsDataStoreImpl.deleteBoolean(SettingsConstants.BLUR)
settingsDataStoreImpl.deleteInt(SettingsConstants.BLUR_PERCENTAGE)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.FIRST_SET)
settingsDataStoreImpl.deleteString(SettingsConstants.NEXT_SET_TIME_1)
settingsDataStoreImpl.deleteString(SettingsConstants.NEXT_SET_TIME_2)
_state.update {
it.copy(
@@ -1,7 +1,11 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen
import android.app.AlarmManager
import android.app.WallpaperManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
@@ -28,6 +32,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.anthonyla.paperize.R
@@ -357,8 +362,23 @@ fun WallpaperScreen(
onDismiss = { openBottomSheet = false },
onSelect = { album ->
openBottomSheet = false
onSelectAlbum(album)
onScheduleWallpaperChanger1(interval1)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val alarmManager = ContextCompat.getSystemService(context, AlarmManager::class.java)
if (alarmManager?.canScheduleExactAlarms() == false) {
Intent().also { intent ->
intent.action = Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM
context.startActivity(intent)
}
}
else {
onSelectAlbum(album)
onScheduleWallpaperChanger1(interval1)
}
}
else {
onSelectAlbum(album)
onScheduleWallpaperChanger1(interval1)
}
},
animate = animate
)
@@ -1,6 +1,5 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import android.content.Context
import android.os.Build
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
@@ -35,8 +34,8 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.isValidUri
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.skydoves.landscapist.ImageOptions
@@ -55,17 +54,6 @@ fun AlbumBottomSheet(
onSelect: (AlbumWithWallpaperAndFolder) -> Unit,
animate: Boolean
) {
fun isValidUri(context: Context, uriString: String?): Boolean {
val uri = uriString?.toUri()
return try {
uri?.let {
val inputStream = context.contentResolver.openInputStream(it)
inputStream?.close()
}
true
} catch (e: Exception) { false }
}
val modalBottomSheetState = rememberModalBottomSheetState()
val scope = rememberCoroutineScope()
ModalBottomSheet(
@@ -0,0 +1,15 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager
import com.anthonyla.paperize.core.SettingsConstants
/**
* Data class for storing wallpaper alarm item
* @param timeInMinutes1: Int - time in minutes for home wallpaper or both if scheduled together
* @param timeInMinutes2: Int - time in minutes for lock wallpaper
* @param scheduleSeparately: Boolean - schedule wallpapers separately
*/
data class WallpaperAlarmItem(
val timeInMinutes1: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val timeInMinutes2: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val scheduleSeparately: Boolean = false
)
@@ -0,0 +1,27 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager
interface WallpaperAlarmScheduler {
/**
* Schedule a wallpaper alarm to change the wallpaper
* @param wallpaperAlarmItem the wallpaper alarm item to schedule
* @param origin where the request came from (null if not from a specific origin, 0 if home screen, 1 if lock screen, 2 if both)
* @param changeImmediate whether to change the wallpaper immediately or just schedule the alarm
* @param cancelImmediate whether to cancel all alarms before scheduling the new one
*/
fun scheduleWallpaperAlarm(wallpaperAlarmItem: WallpaperAlarmItem, origin: Int? = null, changeImmediate: Boolean = false, cancelImmediate: Boolean = false)
/**
* Update the wallpaper alarm with new times without changing the wallpaper
*/
fun updateWallpaperAlarm(wallpaperAlarmItem: WallpaperAlarmItem)
/**
* Update the wallpaper without changing the alarm
*/
fun updateWallpaper(scheduleSeparately: Boolean)
/**
* Cancel all wallpaper alarms
*/
fun cancelWallpaperAlarm()
}
@@ -0,0 +1,59 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.data.settings.SettingsDataStore
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
/**
* Receiver for boot and time change events to restart alarm manager
*/
@AndroidEntryPoint
class WallpaperBootAndTimeChangeReceiver : BroadcastReceiver() {
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
override fun onReceive(context: Context, intent: Intent) = goAsync {
try {
if (Intent.ACTION_BOOT_COMPLETED == intent.action || Intent.ACTION_TIME_CHANGED == intent.action || Intent.ACTION_TIMEZONE_CHANGED == intent.action) {
val scheduler = WallpaperScheduler(context)
val toggleChanger = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
if (toggleChanger) {
val timeInMinutes1 = settingsDataStoreImpl.getInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val timeInMinutes2 = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val scheduleSeparately = settingsDataStoreImpl.getBoolean(SettingsConstants.SCHEDULE_SEPARATELY) ?: false
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = timeInMinutes1,
timeInMinutes2 = timeInMinutes2,
scheduleSeparately = scheduleSeparately
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, false, true)}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
/* https://stackoverflow.com/questions/74111692/run-coroutine-functions-on-broadcast-receiver */
private fun BroadcastReceiver.goAsync(
context: CoroutineContext = EmptyCoroutineContext,
block: suspend CoroutineScope.() -> Unit
) {
val pendingResult = goAsync()
@OptIn(DelicateCoroutinesApi::class)
GlobalScope.launch(context) {
try {
block()
} finally {
pendingResult.finish()
}
}
}
}
@@ -0,0 +1,53 @@
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.WALLPAPER_CHANGE_INTERVAL_DEFAULT
import com.anthonyla.paperize.core.Type
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.WallpaperService1
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.WallpaperService2
import dagger.hilt.android.AndroidEntryPoint
/**
* Receiver for the alarm manager to change wallpaper
*/
@AndroidEntryPoint
class WallpaperReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (context != null) {
val timeInMinutes1 = intent?.getIntExtra("timeInMinutes1", WALLPAPER_CHANGE_INTERVAL_DEFAULT) ?: WALLPAPER_CHANGE_INTERVAL_DEFAULT
val timeInMinutes2 = intent?.getIntExtra("timeInMinutes2", WALLPAPER_CHANGE_INTERVAL_DEFAULT) ?: WALLPAPER_CHANGE_INTERVAL_DEFAULT
val scheduleSeparately = intent?.getBooleanExtra("scheduleSeparately", false) ?: false
val type = intent?.getIntExtra("type", Type.BOTH.ordinal) ?: Type.BOTH.ordinal
val serviceIntent = Intent().apply {
putExtra("timeInMinutes1", timeInMinutes1)
putExtra("timeInMinutes2", timeInMinutes2)
putExtra("scheduleSeparately", scheduleSeparately)
putExtra("type", type)
}
if (type == Type.BOTH.ordinal || type == Type.HOME.ordinal) {
serviceIntent.setClass(context, WallpaperService1::class.java).apply {
action = WallpaperService1.Actions.START.toString()
}
} else {
serviceIntent.setClass(context, WallpaperService2::class.java).apply {
action = WallpaperService2.Actions.START.toString()
}
}
context.startService(serviceIntent)
// Schedule next alarm for next wallpaper change
val origin = intent?.getIntExtra("origin", -1)?.takeIf { it != -1 }
WallpaperScheduler(context).scheduleWallpaperAlarm(
WallpaperAlarmItem(
timeInMinutes1 = timeInMinutes1,
timeInMinutes2 = timeInMinutes2,
scheduleSeparately = scheduleSeparately
),
origin
)
}
}
}
@@ -0,0 +1,210 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import com.anthonyla.paperize.core.Type
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.WallpaperService1
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.WallpaperService2
import java.time.LocalDateTime
import java.time.ZoneId
/**
* This class is responsible for scheduling wallpaper alarms.
* It uses the AlarmManager to schedule alarms for the WallpaperReceiver.
* It also uses the WallpaperService to change the wallpaper due to receiver limitations.
*/
class WallpaperScheduler (
private val context: Context,
): WallpaperAlarmScheduler {
private val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
override fun scheduleWallpaperAlarm(wallpaperAlarmItem: WallpaperAlarmItem, origin: Int?, changeImmediate: Boolean, cancelImmediate: Boolean) {
if (cancelImmediate) cancelWallpaperAlarm()
else {
when(origin) {
Type.HOME.ordinal -> cancelAlarm(Type.HOME)
Type.LOCK.ordinal -> cancelAlarm(Type.LOCK)
null -> {
cancelAlarm(Type.HOME)
cancelAlarm(Type.LOCK)
cancelAlarm(Type.BOTH)
}
}
}
if (wallpaperAlarmItem.scheduleSeparately) {
when (origin) {
Type.HOME.ordinal -> {
if (changeImmediate) changeWallpaperImmediate(wallpaperAlarmItem, Type.HOME)
scheduleWallpaper(wallpaperAlarmItem, Type.HOME, origin)
}
Type.LOCK.ordinal -> {
if (changeImmediate) changeWallpaperImmediate(wallpaperAlarmItem, Type.LOCK)
scheduleWallpaper(wallpaperAlarmItem, Type.LOCK, origin)
}
null -> {
if (changeImmediate) {
changeWallpaperImmediate(wallpaperAlarmItem, Type.HOME)
changeWallpaperImmediate(wallpaperAlarmItem, Type.LOCK)
}
scheduleWallpaper(wallpaperAlarmItem, Type.HOME, Type.HOME.ordinal)
scheduleWallpaper(wallpaperAlarmItem, Type.LOCK, Type.LOCK.ordinal)
}
}
}
else {
if (changeImmediate) changeWallpaperImmediate(wallpaperAlarmItem, Type.BOTH)
scheduleWallpaper(wallpaperAlarmItem, Type.BOTH)
}
}
override fun updateWallpaperAlarm(wallpaperAlarmItem: WallpaperAlarmItem) {
cancelWallpaperAlarm()
if (wallpaperAlarmItem.scheduleSeparately) {
scheduleWallpaper(wallpaperAlarmItem, Type.HOME, null, true)
scheduleWallpaper(wallpaperAlarmItem, Type.LOCK, null, true)
}
else {
scheduleWallpaper(wallpaperAlarmItem, Type.BOTH, null, true)
}
}
override fun updateWallpaper(scheduleSeparately: Boolean) {
if (scheduleSeparately) {
updateWallpaper(Type.HOME)
updateWallpaper(Type.LOCK)
}
else {
updateWallpaper(Type.BOTH)
}
}
override fun cancelWallpaperAlarm() {
cancelAlarm(Type.HOME)
cancelAlarm(Type.LOCK)
cancelAlarm(Type.BOTH)
}
/**
* Schedules the wallpaper alarm based on type and time
*/
private fun scheduleWallpaper(wallpaperAlarmItem: WallpaperAlarmItem, type: Type, origin: Int? = null, update: Boolean = false) {
val nextTime = when (type) {
Type.HOME, Type.BOTH -> LocalDateTime.now().plusMinutes(wallpaperAlarmItem.timeInMinutes1.toLong())
Type.LOCK -> LocalDateTime.now().plusMinutes(wallpaperAlarmItem.timeInMinutes2.toLong())
}
val intent = Intent(context, WallpaperReceiver::class.java).apply {
putExtra("timeInMinutes1", wallpaperAlarmItem.timeInMinutes1)
putExtra("timeInMinutes2", wallpaperAlarmItem.timeInMinutes2)
putExtra("scheduleSeparately", wallpaperAlarmItem.scheduleSeparately)
putExtra("type", type.ordinal)
putExtra("origin", origin)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (!alarmManager.canScheduleExactAlarms()) {
Intent().also {
it.action = Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM
context.startActivity(it)
}
}
else {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
nextTime.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000,
PendingIntent.getBroadcast(
context,
type.ordinal,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
)
}
}
else {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
nextTime.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000,
PendingIntent.getBroadcast(
context,
type.ordinal,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
)
}
if (update) {
val serviceIntent = Intent().apply {
putExtra("timeInMinutes1", wallpaperAlarmItem.timeInMinutes1)
putExtra("timeInMinutes2", wallpaperAlarmItem.timeInMinutes2)
putExtra("scheduleSeparately", wallpaperAlarmItem.scheduleSeparately)
putExtra("type", type.ordinal)
}
if (type == Type.BOTH || type == Type.HOME) {
serviceIntent.setClass(context, WallpaperService1::class.java).apply {
action = WallpaperService1.Actions.REQUEUE.toString()
}
} else {
serviceIntent.setClass(context, WallpaperService2::class.java).apply {
action = WallpaperService2.Actions.REQUEUE.toString()
}
}
context.startService(serviceIntent)
}
}
/**
* Use the service to change the wallpaper
*/
private fun changeWallpaperImmediate(wallpaperAlarmItem: WallpaperAlarmItem, type: Type) {
val serviceIntent = Intent().apply {
putExtra("timeInMinutes1", wallpaperAlarmItem.timeInMinutes1)
putExtra("timeInMinutes2", wallpaperAlarmItem.timeInMinutes2)
putExtra("scheduleSeparately", wallpaperAlarmItem.scheduleSeparately)
putExtra("type", type.ordinal)
}
if (type == Type.BOTH || type == Type.HOME) {
serviceIntent.setClass(context, WallpaperService1::class.java).apply {
action = WallpaperService1.Actions.START.toString()
}
} else {
serviceIntent.setClass(context, WallpaperService2::class.java).apply {
action = WallpaperService2.Actions.START.toString()
}
}
context.startService(serviceIntent)
}
/**
* Updates the wallpaper without changing the alarm
*/
private fun updateWallpaper(type: Type) {
val serviceIntent = Intent()
if (type == Type.BOTH || type == Type.HOME) {
serviceIntent.setClass(context, WallpaperService1::class.java).apply {
action = WallpaperService1.Actions.UPDATE.toString()
}
} else {
serviceIntent.setClass(context, WallpaperService2::class.java).apply {
action = WallpaperService2.Actions.UPDATE.toString()
}
}
context.startService(serviceIntent)
}
/**
* Cancels the alarm based on type
*/
private fun cancelAlarm(type: Type) {
val pendingIntent = PendingIntent.getBroadcast(
context,
type.ordinal,
Intent(context, WallpaperReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
alarmManager.cancel(pendingIntent)
}
}
@@ -1,29 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaper_service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.data.settings.SettingsDataStore
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.runBlocking
import javax.inject.Inject
@AndroidEntryPoint
class WallpaperBootReceiver : BroadcastReceiver() {
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
override fun onReceive(context: Context, intent: Intent) {
if (Intent.ACTION_BOOT_COMPLETED == intent.action) {
val serviceIntent = Intent(context, WallpaperService::class.java)
serviceIntent.action = WallpaperService.Actions.START.toString()
runBlocking {
val timeInMinutes1 = settingsDataStoreImpl.getInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val timeInMinutes2 = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val scheduleSeparately = settingsDataStoreImpl.getBoolean(SettingsConstants.SCHEDULE_SEPARATELY) ?: false
serviceIntent.putExtra("timeInMinutes1", timeInMinutes1)
serviceIntent.putExtra("timeInMinutes2", timeInMinutes2)
serviceIntent.putExtra("scheduleSeparately", scheduleSeparately)
}
context.startForegroundService(serviceIntent)
}
}
}
@@ -0,0 +1,724 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaper_service
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.app.WallpaperManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.IBinder
import android.util.DisplayMetrics
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
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.blurBitmap
import com.anthonyla.paperize.core.calculateInSampleSize
import com.anthonyla.paperize.core.darkenBitmap
import com.anthonyla.paperize.core.fillBitmap
import com.anthonyla.paperize.core.fitBitmap
import com.anthonyla.paperize.core.getImageDimensions
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.core.stretchBitmap
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
import com.anthonyla.paperize.feature.wallpaper.presentation.MainActivity
import com.lazygeniouz.dfc.file.DocumentFileCompat
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 java.io.IOException
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import javax.inject.Inject
import kotlin.math.min
/**
* Main service for changing the wallpaper if wallpapers are scheduled together
*/
@AndroidEntryPoint
class WallpaperService1: Service() {
private val handleThread = HandlerThread("MyThread1")
private lateinit var workerHandler: Handler
@Inject lateinit var selectedRepository: SelectedAlbumRepository
@Inject lateinit var albumRepository: AlbumRepository
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
private var scheduleSeparately: Boolean = false
private var timeInMinutes1: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
private var timeInMinutes2: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
private var nextSetTime1: LocalDateTime? = null
private var nextSetTime2: LocalDateTime? = null
private var nextSetTime: LocalDateTime? = null
enum class Actions {
START,
REQUEUE,
UPDATE
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
handleThread.start()
workerHandler = Handler(handleThread.looper)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent != null) {
when (intent.action) {
Actions.START.toString() -> {
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
timeInMinutes2 = intent.getIntExtra("timeInMinutes2", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
val setHomeOrLock = if (scheduleSeparately) {
when (intent.getIntExtra("type", Type.BOTH.ordinal)) {
Type.HOME.ordinal -> true
Type.LOCK.ordinal -> false
else -> null
}
} else { null }
workerTaskStart(setHomeOrLock)
}
Actions.REQUEUE.toString() -> {
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
timeInMinutes2 = intent.getIntExtra("timeInMinutes2", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
workerTaskRequeue()
}
Actions.UPDATE.toString() -> {
workerTaskUpdate()
}
}
}
return START_NOT_STICKY
}
override fun onDestroy() {
super.onDestroy()
workerHandler.removeCallbacksAndMessages(null)
handleThread.quitSafely()
}
private fun workerTaskStart(setHomeOrLock: Boolean? = null) {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
refreshAlbum(this@WallpaperService1)
delay(2000)
changeWallpaper(this@WallpaperService1, setHomeOrLock)
}
stopSelf()
}
}
private fun workerTaskRequeue() {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
nextSetTime = (if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2)
val notification = createNotification()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notification?.let { notificationManager.notify(1, it) }
}
stopSelf()
}
}
private fun workerTaskUpdate() {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
updateCurrentWallpaper(this@WallpaperService1)
}
stopSelf()
}
}
/**
* Creates a notification for the wallpaper service
*/
private fun createNotification(): Notification? {
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
if (nextSetTime != null) {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 3, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return NotificationCompat.Builder(this, "wallpaper_service_channel")
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.next_wallpaper_change, nextSetTime!!.format(formatter)))
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build()
}
return null
}
/**
* 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, setHomeOrLock: Boolean? = null) {
try {
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum == null) {
onDestroy()
return
}
else {
val toggled = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.LOCK_WALLPAPER) ?: false
nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
if (!toggled || (!setHome && !setLock)) {
onDestroy()
return
}
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val currentTime = LocalDateTime.now()
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
if (setHomeOrLock == null) {
nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong())
nextSetTime2 = nextSetTime1
nextSetTime = nextSetTime1
nextSetTime?.let { settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) }
}
else {
if (setHomeOrLock) { nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong()) }
else { nextSetTime2 = currentTime.plusMinutes(timeInMinutes2.toLong()) }
nextSetTime = if (nextSetTime1 == null && nextSetTime2 != null) {
nextSetTime2
} else if (nextSetTime1 != null && nextSetTime2 == null) {
nextSetTime1
} else {
if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2
}
nextSetTime?.let { settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) }
}
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_1, nextSetTime1.toString())
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_2, nextSetTime2.toString())
val notification = createNotification()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notification?.let { notificationManager.notify(1, it) }
val scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL
val darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false
val darkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 100
val blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false
val blurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.BLUR_PERCENTAGE) ?: 0
selectedAlbum.let { it ->
if (setHomeOrLock != null) {
var wallpaper = if (setHomeOrLock) it.album.homeWallpapersInQueue.firstOrNull() else it.album.lockWallpapersInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = setHomeOrLock,
blur = blur,
blurPercent = blurPercentage
)) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = if (setHomeOrLock) it.album.homeWallpapersInQueue.drop(1) else it.album.homeWallpapersInQueue,
lockWallpapersInQueue = if (!setHomeOrLock) it.album.lockWallpapersInQueue.drop(1) else it.album.lockWallpapersInQueue,
currentHomeWallpaper = if (setHomeOrLock) wallpaper else it.album.currentHomeWallpaper,
currentLockWallpaper = if (!setHomeOrLock) wallpaper else it.album.currentLockWallpaper
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = if (setHomeOrLock) it.album.homeWallpapersInQueue.drop(1) else it.album.homeWallpapersInQueue,
lockWallpapersInQueue = if (!setHomeOrLock) it.album.lockWallpapersInQueue.drop(1) else it.album.lockWallpapersInQueue,
currentHomeWallpaper = if (setHomeOrLock) wallpaper else it.album.currentHomeWallpaper,
currentLockWallpaper = if (!setHomeOrLock) wallpaper else it.album.currentLockWallpaper
)
)
)
}
}
// No more wallpapers in the queue -- reshuffle the wallpapers
else {
val newWallpaperInQueue = it.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpaperInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = setHomeOrLock,
blur = blur,
blurPercent = blurPercentage
)
) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = if (setHomeOrLock) newWallpaperInQueue.drop(1) else it.album.homeWallpapersInQueue,
lockWallpapersInQueue = if (!setHomeOrLock) newWallpaperInQueue.drop(1) else it.album.lockWallpapersInQueue,
currentHomeWallpaper = if (setHomeOrLock) wallpaper else it.album.currentHomeWallpaper,
currentLockWallpaper = if (!setHomeOrLock) wallpaper else it.album.currentLockWallpaper
),
wallpapers = it.wallpapers.filter { it == it1 }
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = if (setHomeOrLock) newWallpaperInQueue.drop(1) else it.album.homeWallpapersInQueue,
lockWallpapersInQueue = if (!setHomeOrLock) newWallpaperInQueue.drop(1) else it.album.lockWallpapersInQueue,
currentHomeWallpaper = if (setHomeOrLock) wallpaper else it.album.currentHomeWallpaper,
currentLockWallpaper = if (!setHomeOrLock) wallpaper else it.album.currentLockWallpaper
)
)
)
}
} else { onDestroy() }
}
}
else {
var wallpaper = it.album.homeWallpapersInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
blur = blur,
blurPercent = blurPercentage
)) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.drop(1),
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper },
currentHomeWallpaper = null,
currentLockWallpaper = null
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.drop(1),
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper },
currentHomeWallpaper = wallpaper,
currentLockWallpaper = wallpaper
)
)
)
}
}
// No more wallpapers in the queue -- reshuffle the wallpapers
else {
val newWallpaperInQueue = it.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpaperInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = setHomeOrLock,
blur = blur,
blurPercent = blurPercentage
)
) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.drop(1),
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper },
currentHomeWallpaper = null,
currentLockWallpaper = null
),
wallpapers = it.wallpapers.filter { it == it1 }
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = newWallpaperInQueue.drop(1),
currentHomeWallpaper = wallpaper,
currentLockWallpaper = wallpaper
)
)
)
}
} else { onDestroy() }
}
}
}
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in changing wallpaper", e)
}
}
private suspend fun updateCurrentWallpaper(context: Context) {
try {
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum == null) {
onDestroy()
return
}
else {
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.LOCK_WALLPAPER) ?: false
if (!setHome && !setLock) {
onDestroy()
return
}
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val time = LocalDateTime.now()
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, time.format(formatter))
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, time.plusMinutes(timeInMinutes1.toLong()).format(formatter))
val scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL
val darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false
val darkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 100
val blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false
val blurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.BLUR_PERCENTAGE) ?: 0
selectedAlbum.let { it ->
val wallpaper1 = it.album.currentHomeWallpaper
val wallpaper2 = it.album.currentLockWallpaper
if (wallpaper1 != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper1.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = true,
blur = blur,
blurPercent = blurPercentage
)) {
selectedAlbum.wallpapers.firstOrNull{ it.wallpaperUri == wallpaper1 }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.filter { it != wallpaper1 },
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper1 },
currentHomeWallpaper = null
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
}
}
if (wallpaper2 != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper2.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = false,
blur = blur,
blurPercent = blurPercentage
)) {
selectedAlbum.wallpapers.firstOrNull{ it.wallpaperUri == wallpaper2 }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.filter { it != wallpaper1 },
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper1 },
currentLockWallpaper = null
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
}
}
}
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in updating", e)
}
}
/**
* Sets the wallpaper to the given uri
*/
private fun setWallpaper(
context: Context,
wallpaper: Uri,
darken: Boolean,
darkenPercent: Int,
scaling: ScalingConstants,
setHome: Boolean, setLock: Boolean,
setLockOrHome: Boolean? = null,
blur: Boolean = false,
blurPercent: Int
): Boolean {
val wallpaperManager = WallpaperManager.getInstance(context)
try {
val imageSize = wallpaper.getImageDimensions(context) ?: return false
val aspectRatio = imageSize.height.toFloat() / imageSize.width.toFloat()
val device = context.resources.displayMetrics
val targetWidth = min(4 * device.widthPixels, imageSize.width)
val targetHeight = (targetWidth * aspectRatio).toInt()
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
try {
val source = ImageDecoder.createSource(context.contentResolver, wallpaper)
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
decoder.setTargetSize(targetWidth, targetHeight)
decoder.isMutableRequired = true
}
} catch (e: Exception) {
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
val options = BitmapFactory.Options().apply {
inSampleSize = calculateInSampleSize(imageSize, targetWidth, targetHeight)
inMutable = true
}
BitmapFactory.decodeStream(inputStream, null, options)
}
}
}
else {
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
val options = BitmapFactory.Options().apply {
inSampleSize = calculateInSampleSize(imageSize, targetWidth, targetHeight)
inMutable = true
}
BitmapFactory.decodeStream(inputStream, null, options)
}
}
if (bitmap == null) return false
else {
processBitmap(device, bitmap, darken, darkenPercent, scaling, blur, blurPercent)?.let { image ->
when {
setLockOrHome == true -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_SYSTEM)
setLockOrHome == false -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_LOCK)
setHome && setLock -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_LOCK or WallpaperManager.FLAG_SYSTEM)
setHome -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_SYSTEM)
setLock -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_LOCK)
else -> {}
}
image.recycle()
}
bitmap.recycle()
return true
}
} catch (e: IOException) {
Log.e("PaperizeWallpaperChanger", "Error setting wallpaper", e)
return false
}
}
/**
* Darkens the bitmap by the given percentage and returns it
* 0 - lightest, 100 - darkest
*/
private fun processBitmap(
device: DisplayMetrics,
source: Bitmap, darken: Boolean,
darkenPercent: Int,
scaling: ScalingConstants,
blur: Boolean,
blurPercent: Int
): Bitmap? {
try {
var processedBitmap = source
// Apply wallpaper scaling effects
processedBitmap = when (scaling) {
ScalingConstants.FILL -> fillBitmap(processedBitmap, device.widthPixels, device.heightPixels)
ScalingConstants.FIT -> fitBitmap(processedBitmap, device.widthPixels, device.heightPixels)
ScalingConstants.STRETCH -> stretchBitmap(processedBitmap, device.widthPixels, device.heightPixels)
}
// Apply brightness effect
if (darken && darkenPercent < 100) {
processedBitmap = darkenBitmap(processedBitmap, darkenPercent)
}
// Apply blur effect
if (blur && blurPercent > 0) {
processedBitmap = blurBitmap(processedBitmap, blurPercent)
}
return processedBitmap
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error darkening bitmap", e)
return null
}
}
private fun refreshAlbum(context: Context) {
CoroutineScope(Dispatchers.IO).launch {
try {
var albumWithWallpapers = albumRepository.getAlbumsWithWallpaperAndFolder().first()
albumWithWallpapers.forEach { albumWithWallpaper ->
// Delete wallpaper if the URI is invalid
val invalidWallpapers = albumWithWallpaper.wallpapers.filterNot { wallpaper ->
val file = DocumentFile.fromSingleUri(context, wallpaper.wallpaperUri.toUri())
file?.exists() == true
}
if (invalidWallpapers.isNotEmpty()) {
albumRepository.deleteWallpaperList(invalidWallpapers)
}
// Update folder cover uri and wallpapers uri
albumWithWallpaper.folders.forEach { folder ->
try {
DocumentFileCompat.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory ->
if (!folderDirectory.isDirectory()) {
albumRepository.deleteFolder(folder)
} else {
val wallpapers = getWallpaperFromFolder(folder.folderUri, context)
val folderCoverFile = folder.coverUri?.let { DocumentFile.fromSingleUri(context, it.toUri()) }
val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull()
albumRepository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers))
}
}
} catch (e: Exception) {
DocumentFile.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory ->
if (!folderDirectory.isDirectory) {
albumRepository.deleteFolder(folder)
} else {
val wallpapers = getWallpaperFromFolder(folder.folderUri, context)
val folderCoverFile = folder.coverUri?.let { DocumentFile.fromSingleUri(context, it.toUri()) }
val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull()
albumRepository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers))
}
}
}
}
// Delete empty albums
if (albumWithWallpaper.wallpapers.isEmpty() && albumWithWallpaper.folders.all { it.wallpapers.isEmpty() }) {
albumRepository.deleteAlbum(albumWithWallpaper.album)
}
}
// Update selected album
albumWithWallpapers = albumRepository.getAlbumsWithWallpaperAndFolder().first()
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum != null) {
albumWithWallpapers.find { it.album.initialAlbumName == selectedAlbum.album.initialAlbumName }
?.let { foundAlbum ->
val albumNameHashCode = foundAlbum.album.initialAlbumName.hashCode()
val wallpapers: List<Wallpaper> =
foundAlbum.wallpapers + foundAlbum.folders.flatMap { folder ->
folder.wallpapers.map { wallpaper ->
Wallpaper(
initialAlbumName = foundAlbum.album.initialAlbumName,
wallpaperUri = wallpaper,
key = wallpaper.hashCode() + albumNameHashCode,
)
}
}
val wallpapersUri = wallpapers.map { it.wallpaperUri }.toSet()
if (wallpapersUri.isEmpty()) {
selectedRepository.deleteAll()
onDestroy()
}
else {
val newSelectedAlbum = SelectedAlbum(
album = foundAlbum.album.copy(
homeWallpapersInQueue = if (selectedAlbum.album.homeWallpapersInQueue.firstOrNull() in wallpapersUri) {
val firstElement = selectedAlbum.album.homeWallpapersInQueue.first()
val modifiedWallpapersUri = wallpapersUri.filter { it != firstElement }
listOf(firstElement) + modifiedWallpapersUri.shuffled()
} else { wallpapersUri.shuffled() },
lockWallpapersInQueue = if (selectedAlbum.album.lockWallpapersInQueue.firstOrNull() in wallpapersUri) {
val firstElement = selectedAlbum.album.lockWallpapersInQueue.first()
val modifiedWallpapersUri = wallpapersUri.filter { it != firstElement }
listOf(firstElement) + modifiedWallpapersUri.shuffled()
} else { wallpapersUri.shuffled() },
currentHomeWallpaper = if (selectedAlbum.album.currentHomeWallpaper in wallpapersUri) selectedAlbum.album.currentHomeWallpaper else selectedAlbum.album.homeWallpapersInQueue.firstOrNull { it in wallpapersUri },
currentLockWallpaper = if (selectedAlbum.album.currentLockWallpaper in wallpapersUri) selectedAlbum.album.currentLockWallpaper else selectedAlbum.album.lockWallpapersInQueue.firstOrNull { it in wallpapersUri }
),
wallpapers = wallpapers
)
selectedRepository.upsertSelectedAlbum(newSelectedAlbum)
}
} ?: run { onDestroy() }
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error refreshing album", e)
}
}
}
}
@@ -13,8 +13,8 @@ import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.IBinder
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import androidx.core.app.NotificationCompat
@@ -23,6 +23,7 @@ import androidx.documentfile.provider.DocumentFile
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.blurBitmap
import com.anthonyla.paperize.core.calculateInSampleSize
import com.anthonyla.paperize.core.darkenBitmap
@@ -51,29 +52,26 @@ import java.time.format.FormatStyle
import javax.inject.Inject
import kotlin.math.min
/**
* Used in conjunction with [WallpaperService1] to schedule home screen and lock screen separately
*/
@AndroidEntryPoint
class WallpaperService: Service() {
class WallpaperService2: Service() {
private val handleThread = HandlerThread("MyThread2")
private lateinit var workerHandler: Handler
@Inject lateinit var selectedRepository: SelectedAlbumRepository
@Inject lateinit var albumRepository: AlbumRepository
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
private val handler1 = Handler(Looper.getMainLooper())
private val handler2 = Handler(Looper.getMainLooper())
private lateinit var runnableCode1: Runnable
private lateinit var runnableCode2: Runnable
private var scheduleSeparately: Boolean = false
private var timeInMinutes1: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
private var timeInMinutes2: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
private var nextSetTime1: LocalDateTime? = null
private var nextSetTime2: LocalDateTime? = null
private var scheduleSeparately: Boolean = false
private var lastRan1: LocalDateTime? = null
private var lastRan2: LocalDateTime? = null
private var refresherTimer = LocalDateTime.now()
private var nextSetTime: LocalDateTime? = null
enum class Actions {
START,
REQUEUE,
STOP,
UPDATE
}
@@ -81,291 +79,99 @@ class WallpaperService: Service() {
return null
}
/**
* Set up the runnable code to change the wallpaper to prevent runnableCode from being null
*/
override fun onCreate() {
super.onCreate()
startForeground(1, createNotification())
runnableCode1 = object : Runnable {
override fun run() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, true)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler1.postDelayed(self, timeInMinutes1 * 60 * 1000L)
}
}
}
}
runnableCode2 = object : Runnable {
override fun run() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, false)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler2.postDelayed(self, timeInMinutes2 * 60 * 1000L + 10000)
}
}
}
}
handleThread.start()
workerHandler = Handler(handleThread.looper)
}
/**
* Start the service and schedule the wallpaper change
*/
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when(intent?.action) {
Actions.START.toString() -> {
handler1.removeCallbacks(runnableCode1)
handler2.removeCallbacks(runnableCode2)
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
timeInMinutes2 = intent.getIntExtra("timeInMinutes2", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
nextSetTime1 = null
nextSetTime2 = null
lastRan1 = null
lastRan2 = null
refresherTimer = LocalDateTime.now()
if (!scheduleSeparately) {
runnableCode1 = object : Runnable {
override fun run() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, null)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler1.postDelayed(self, timeInMinutes1 * 60 * 1000L)
}
}
if (intent != null) {
when (intent.action) {
Actions.START.toString() -> {
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
timeInMinutes2 = intent.getIntExtra("timeInMinutes2", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
val setHomeOrLock = if (scheduleSeparately) {
when (intent.getIntExtra("type", Type.BOTH.ordinal)) {
Type.HOME.ordinal -> true
Type.LOCK.ordinal -> false
else -> null
}
}
handler1.postDelayed(runnableCode1, 1000)
} else { null }
workerTaskStart(setHomeOrLock)
}
else {
runnableCode1 = object : Runnable {
override fun run() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, true)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler1.postDelayed(self, timeInMinutes1 * 60 * 1000L)
}
}
}
}
handler1.postDelayed(runnableCode1, 1000)
runnableCode2 = object : Runnable {
override fun run() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, false)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler2.postDelayed(self, timeInMinutes2 * 60 * 1000L + 10000)
}
}
}
}
handler2.postDelayed(runnableCode2, 5000)
Actions.REQUEUE.toString() -> {
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
timeInMinutes2 = intent.getIntExtra("timeInMinutes2", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
workerTaskRequeue()
}
}
Actions.REQUEUE.toString() -> {
handler1.removeCallbacks(runnableCode1)
handler2.removeCallbacks(runnableCode2)
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
timeInMinutes2 = intent.getIntExtra("timeInMinutes2", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
nextSetTime1 = null
nextSetTime2 = null
lastRan1 = null
lastRan2 = null
refresherTimer = LocalDateTime.now()
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val currentTime = LocalDateTime.now()
CoroutineScope(Dispatchers.IO).launch {
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
if (scheduleSeparately) {
nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong())
nextSetTime2 = currentTime.plusMinutes(timeInMinutes2.toLong())
val earliestTime = (if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2)!!.format(formatter)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, earliestTime)
}
else {
nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong())
nextSetTime2 = nextSetTime1
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, currentTime.plusMinutes(timeInMinutes1.toLong()).format(formatter))
}
Actions.UPDATE.toString() -> {
workerTaskUpdate()
}
val notification = createNotification()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
if (!scheduleSeparately) {
runnableCode1 = object : Runnable {
override fun run() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, null)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler1.postDelayed(self, timeInMinutes1 * 60 * 1000L)
}
}
}
}
handler1.postDelayed(runnableCode1, timeInMinutes1 * 60 * 1000L)
}
else {
runnableCode1 = object : Runnable {
override fun run() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, true)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler1.postDelayed(self, timeInMinutes1 * 60 * 1000L)
}
}
}
}
handler1.postDelayed(runnableCode1, timeInMinutes1 * 60 * 1000L)
runnableCode2 = object : Runnable {
override fun run() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, false)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler2.postDelayed(self, timeInMinutes2 * 60 * 1000L + 10000)
}
}
}
}
handler2.postDelayed(runnableCode2, timeInMinutes2 * 60 * 1000L + 10000)
}
}
Actions.UPDATE.toString() -> {
CoroutineScope(Dispatchers.IO).launch {
try {
updateCurrentWallpaper(this@WallpaperService)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in changing brightness", e)
}
}
}
Actions.STOP.toString() -> {
handler1.removeCallbacks(runnableCode1)
handler2.removeCallbacks(runnableCode2)
CoroutineScope(Dispatchers.IO).launch {
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, "")
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, "")
}
stopSelf()
}
}
return START_STICKY
return START_NOT_STICKY
}
/**
* Clean up the service when it is destroyed
*/
override fun onDestroy() {
super.onDestroy()
handler1.removeCallbacks(runnableCode1)
handler2.removeCallbacks(runnableCode2)
CoroutineScope(Dispatchers.IO).launch {
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, "")
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, "")
workerHandler.removeCallbacksAndMessages(null)
handleThread.quitSafely()
}
private fun workerTaskStart(setHomeOrLock: Boolean? = null) {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
delay(3000)
refreshAlbum(this@WallpaperService2)
delay(2000)
changeWallpaper(this@WallpaperService2, setHomeOrLock)
}
stopSelf()
}
}
private fun workerTaskRequeue() {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
nextSetTime = (if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2)
val notification = createNotification()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notification?.let { notificationManager.notify(1, it) }
}
stopSelf()
}
}
private fun workerTaskUpdate() {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
updateCurrentWallpaper(this@WallpaperService2)
}
stopSelf()
}
}
/**
* Creates a notification for the wallpaper service
*/
private fun createNotification(): Notification {
private fun createNotification(): Notification? {
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
var earliestTime = when {
nextSetTime1 != null && nextSetTime2 != null -> (if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2)!!.format(formatter)
nextSetTime1 != null -> nextSetTime1!!.format(formatter)
nextSetTime2 != null -> nextSetTime2!!.format(formatter)
else -> LocalDateTime.now().format(formatter)
if (nextSetTime != null) {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 3, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return NotificationCompat.Builder(this, "wallpaper_service_channel")
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.next_wallpaper_change, nextSetTime!!.format(formatter)))
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build()
}
if (earliestTime != null) { // Edge case where numbers like 2131689515 pass through
if (earliestTime.length <= 10) {
earliestTime = LocalDateTime.now().format(formatter)
}
}
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return NotificationCompat.Builder(this, "wallpaper_service_channel")
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.next_wallpaper_change, earliestTime))
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build()
return null
}
/**
@@ -383,6 +189,8 @@ class WallpaperService: Service() {
val toggled = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.LOCK_WALLPAPER) ?: false
nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
if (!toggled || (!setHome && !setLock)) {
onDestroy()
return
@@ -394,26 +202,30 @@ class WallpaperService: Service() {
if (setHomeOrLock == null) {
nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong())
nextSetTime2 = nextSetTime1
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, currentTime.plusMinutes(timeInMinutes1.toLong()).format(formatter))
nextSetTime = nextSetTime1
nextSetTime?.let { settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) }
}
else {
if (setHomeOrLock) { nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong()) }
else { nextSetTime2 = currentTime.plusMinutes(timeInMinutes2.toLong()) }
if (nextSetTime1 == null && nextSetTime2 != null) {
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, nextSetTime2!!.format(formatter))
nextSetTime = nextSetTime2
}
else if (nextSetTime1 != null && nextSetTime2 == null) {
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, nextSetTime1!!.format(formatter))
nextSetTime = nextSetTime1
}
else {
val earliestTime = if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, earliestTime!!.format(formatter))
nextSetTime = if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2
}
nextSetTime?.let { settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) }
}
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_1, nextSetTime1.toString())
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_2, nextSetTime2.toString())
val notification = createNotification()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
notification?.let { notificationManager.notify(1, it) }
val scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL
val darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false
@@ -700,11 +512,6 @@ class WallpaperService: Service() {
}
}
}
if (wallpaper1 != null || wallpaper2 != null) {
val notification = createNotification()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
}
}
}
} catch (e: Exception) {
@@ -735,10 +542,20 @@ class WallpaperService: Service() {
val targetHeight = (targetWidth * aspectRatio).toInt()
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val source = ImageDecoder.createSource(context.contentResolver, wallpaper)
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
decoder.setTargetSize(targetWidth, targetHeight)
decoder.isMutableRequired = true
try {
val source = ImageDecoder.createSource(context.contentResolver, wallpaper)
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
decoder.setTargetSize(targetWidth, targetHeight)
decoder.isMutableRequired = true
}
} catch (e: Exception) {
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
val options = BitmapFactory.Options().apply {
inSampleSize = calculateInSampleSize(imageSize, targetWidth, targetHeight)
inMutable = true
}
BitmapFactory.decodeStream(inputStream, null, options)
}
}
}
else {
@@ -825,17 +642,37 @@ class WallpaperService: Service() {
albumRepository.deleteWallpaperList(invalidWallpapers)
}
// Update folder wallpapers
// Update folder cover uri and wallpapers uri
albumWithWallpaper.folders.forEach { folder ->
DocumentFileCompat.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory ->
if (!folderDirectory.isDirectory()) {
albumRepository.deleteFolder(folder)
} else {
val wallpapers = getWallpaperFromFolder(folder.folderUri, context)
albumRepository.updateFolder(folder.copy(wallpapers = wallpapers))
try {
DocumentFileCompat.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory ->
if (!folderDirectory.isDirectory()) {
albumRepository.deleteFolder(folder)
} else {
val wallpapers = getWallpaperFromFolder(folder.folderUri, context)
val folderCoverFile = folder.coverUri?.let { DocumentFile.fromSingleUri(context, it.toUri()) }
val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull()
albumRepository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers))
}
}
} catch (e: Exception) {
DocumentFile.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory ->
if (!folderDirectory.isDirectory) {
albumRepository.deleteFolder(folder)
} else {
val wallpapers = getWallpaperFromFolder(folder.folderUri, context)
val folderCoverFile = folder.coverUri?.let { DocumentFile.fromSingleUri(context, it.toUri()) }
val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull()
albumRepository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers))
}
}
}
}
// Delete empty albums
if (albumWithWallpaper.wallpapers.isEmpty() && albumWithWallpaper.folders.all { it.wallpapers.isEmpty() }) {
albumRepository.deleteAlbum(albumWithWallpaper.album)
}
}
// Update selected album
@@ -863,10 +700,18 @@ class WallpaperService: Service() {
else {
val newSelectedAlbum = SelectedAlbum(
album = foundAlbum.album.copy(
homeWallpapersInQueue = wallpapersUri.shuffled(),
lockWallpapersInQueue = wallpapersUri.shuffled(),
currentHomeWallpaper = selectedAlbum.album.currentHomeWallpaper,
currentLockWallpaper = selectedAlbum.album.currentLockWallpaper,
homeWallpapersInQueue = if (selectedAlbum.album.homeWallpapersInQueue.firstOrNull() in wallpapersUri) {
val firstElement = selectedAlbum.album.homeWallpapersInQueue.first()
val modifiedWallpapersUri = wallpapersUri.filter { it != firstElement }
listOf(firstElement) + modifiedWallpapersUri.shuffled()
} else { wallpapersUri.shuffled() },
lockWallpapersInQueue = if (selectedAlbum.album.lockWallpapersInQueue.firstOrNull() in wallpapersUri) {
val firstElement = selectedAlbum.album.lockWallpapersInQueue.first()
val modifiedWallpapersUri = wallpapersUri.filter { it != firstElement }
listOf(firstElement) + modifiedWallpapersUri.shuffled()
} else { wallpapersUri.shuffled() },
currentHomeWallpaper = if (selectedAlbum.album.currentHomeWallpaper in wallpapersUri) selectedAlbum.album.currentHomeWallpaper else selectedAlbum.album.homeWallpapersInQueue.firstOrNull { it in wallpapersUri },
currentLockWallpaper = if (selectedAlbum.album.currentLockWallpaper in wallpapersUri) selectedAlbum.album.currentLockWallpaper else selectedAlbum.album.lockWallpapersInQueue.firstOrNull { it in wallpapersUri }
),
wallpapers = wallpapers
)
+2 -2
View File
@@ -1,6 +1,6 @@
#Tue Apr 30 13:31:42 PDT 2024
#Mon Jun 03 14:51:19 PDT 2024
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+17 -42
View File
@@ -1,42 +1,17 @@
Paperize is a dynamic wallpaper changer application designed to keep your device's aesthetic fresh and exciting
------
Dynamic Wallpaper Changer: Set your wallpaper to change at specific time intervals
Supports Various Image Types: Paperize can handle a wide range of image types
JPEG, PNG, AVIF, WEBP
Folder Support: Organize your wallpapers into folders for auto-updating
Home and Lock Screen Wallpaper: Choose to change either your home screen, lock screen, or both
On-Device Storage: All your wallpapers and settings are stored on your device
------
Technologies
Kotlin - A programming language that is used for Android app development
Jetpack Compose - A declarative UI toolkit for building native Android UI
Material 3 - A UI design system git for modern UI guidelines
Dagger Hilt - A dependency injection library
Room - A persistence library that provides an abstraction layer over SQLite interfacing with Kotlin
AboutLibraries - A library to offer some information of libraries
Lottie Compose - A library that provides Lottie animation support for Jetpack Compose
Landscapist - A Compose and KPP image loading library that streamlines Glide, Coil, and Fresco
Zoomable - A library that provides a zoomable and pannable view, which can be used with any view you want
AnimatedFABMenu - A animated floating action button with Material 3 design
Thanks to the creators and maintainers of the open-source libraries used in this project.
------
Build
This project is built using Kotlin, Java, and Gradle. Here are the steps to build the project:
Prerequisites
Java 8 (1.8)
Android Studio Jellyfish | 2023.3.1 or later
Gradle 8.4.0 or later
Minimum SDK 26
Steps
Open a terminal and run the following git command:
git clone https://github.com/Anthonyy232/Paperize.git
Launch Android Studio and choose Open an existing Android Studio project. Navigate to the cloned repository and select the root folder of the project.
In Android Studio, click on Build -> Generate Signed Bundle / APK and follow the instructions to generate an APK
Alternatively, click ▶ Run and build the app and run it immediately
------
Contributions
All contributions to the app is welcome. Feel free to report any issues and create pull requests for any issues or pull requests.
------
License
Contact on my GitHub profile
Paperize © GNU GPL v3.0
Paperize - A Wallpaper Changer is a dynamic and versatile app that breathes life into your device’s aesthetics. It’s not just a wallpaper changer; it’s a tool that allows you to personalize your device to reflect your style and mood.
Dynamic Wallpaper Changer: With Paperize, you can set your wallpaper to change at specific time intervals. This means your device’s look will always be fresh and exciting.
Advanced Image Manipulation: Paperize isn’t just about changing wallpapers; it’s about enhancing them. You can darken or blur your wallpapers to suit your visual preferences or to make your icons stand out.
Home and Lock Screen Customization: With Paperize, you have the freedom to set your home screen and lock screen wallpapers together or separately, and at the same time or not. This gives you the ultimate control over your device’s look and feel.
Supports Various Image Types: Paperize can handle a wide range of image types, offering you flexibility in your wallpaper choices. Whether it’s a JPEG, PNG, or a GIF, Paperize has got you covered.
Folder Support: Organize your wallpapers into folders for auto-updating. This feature allows you to categorize your wallpapers and have them change automatically, keeping your device’s look organized and cohesive.
On-Device Storage: All your wallpapers and settings are stored on your device, ensuring quick loading times and reducing data usage. Your favorite wallpapers are always just a tap away.
Experience the joy of a personalized device with Paperize - A Wallpaper Changer. Your device, your style.
Privacy policy: https://anthonyy232.github.io/Paperize/
File renamed without changes.

Before

Width:  |  Height:  |  Size: 274 KiB

After

Width:  |  Height:  |  Size: 274 KiB

-17
View File
@@ -1,17 +0,0 @@
<svg width="500" height="500" xmlns="http://www.w3.org/2000/svg">
<g>
<title>Layer 1</title>
<rect id="svg_5" height="607" width="663" y="-34" x="-60" stroke="#000" fill="#ffd9e2"/>
<g stroke="null">
<path d="m119.78444,143.16459c0.11656,1.91205 -0.53054,3.18387 -2.80906,3.34143c-1.6221,0.11219 -2.54328,1.03358 -2.44518,2.62779c0.10305,1.67496 1.42508,2.11774 2.87671,2.31725c4.0939,0.56267 8.0905,-0.00456 11.98235,-1.16837c7.29126,-2.18035 14.89214,-3.0969 22.23888,-5.03046c2.05032,-0.5396 4.7959,-0.58306 5.28942,-3.01558c0.45311,-2.23322 -1.28083,-3.83701 -3.26363,-5.01267c-0.33551,-0.1989 -0.48119,-0.6869 -0.94738,-1.39481c4.71844,-1.85535 9.53209,-2.19578 14.26141,-2.72721c19.58353,-2.20064 39.27088,-3.5615 58.75084,-6.60577c2.57759,-0.40281 5.05381,-1.47622 7.94736,-0.83846c-7.10148,4.43247 -14.24986,8.73011 -22.21438,12.05754c2.61629,-0.31262 5.24287,-0.56347 7.84598,-0.95522c2.61745,-0.3939 5.20201,-0.98324 7.81736,-1.39225c33.5526,-5.24712 63.83623,-18.76206 93.72151,-33.33278c8.64355,-4.21419 17.57783,-7.82017 26.90464,-10.51625c5.23529,-1.51338 10.0813,-1.19772 15.02543,1.22759c11.07335,5.4319 18.44075,14.03776 23.98902,24.3228c0.32196,0.59681 0.50962,1.22914 0.12468,2.10062c-1.81322,0.3254 -3.91738,1.24051 -3.68053,-2.09668c0.05804,-0.81698 -0.25871,-1.65717 -0.98273,-2.00737c-5.56694,-2.69275 -10.38737,-7.44869 -17.79346,-4.32978c-5.12391,2.15783 -10.84001,2.99453 -15.94262,5.60911c1.13833,2.07772 2.79756,2.52964 4.95192,2.04283c0.88797,-0.20063 1.83219,-0.22794 2.75206,-0.23893c2.04549,-0.02446 3.26261,0.97104 3.57241,2.88223c0.33678,2.07798 -1.22153,2.64071 -2.8658,3.03092c-5.94021,1.40968 -11.89036,2.78136 -17.83277,4.18267c-14.13923,3.33428 -27.79023,8.26262 -41.87605,11.73552c-20.22402,4.98626 -40.48405,9.91898 -61.52902,10.75184c-3.06609,0.12133 -6.11872,0.54962 -9.2049,1.13323c4.58767,1.01725 8.86239,3.01912 13.92696,2.04332c4.15397,-0.80035 8.50018,-0.73454 12.76638,-0.96792c13.54607,-0.74108 26.82457,-2.89149 39.79019,-6.72001c1.64558,-0.4859 3.27071,-1.03414 4.90968,-1.54067c0.07867,-0.02431 0.19987,0.07574 0.82311,0.33478c-3.22293,3.60117 -7.66899,5.28028 -12.49081,7.76778c3.42757,0.96266 5.73927,0.12078 7.99421,-0.281c17.61167,-3.1379 34.68305,-8.35585 52.08109,-12.32842c14.87889,-3.39737 29.85381,-5.73797 45.23525,-5.16274c3.95771,0.14799 7.8079,0.72526 11.63381,1.55591c2.1816,0.47362 3.96114,1.5678 5.49162,3.22461c7.92537,8.57912 11.6946,18.79346 13.30524,29.89212c0.36021,2.48228 0.72521,4.96394 1.23284,8.43684c-5.62883,-2.32491 -10.61575,-4.38466 -15.77325,-6.51487c1.07699,-1.20931 2.18427,-0.69935 3.13574,-0.84125c1.40234,-0.20917 3.4607,0.40708 3.69569,-1.51994c0.19732,-1.61816 -0.66607,-3.33752 -2.48166,-4.00214c-2.79557,-1.02331 -5.62752,-2.03491 -8.53386,-2.69388c-16.72976,-3.79344 -33.46495,-2.92373 -50.17209,0.20969c-10.65248,1.99787 -21.23183,4.28383 -31.55884,7.52009c-0.65696,0.20586 -1.3343,0.37685 -1.95522,0.65779c-1.42368,0.64425 -2.76565,1.52894 -2.30877,3.2331c0.48751,1.81829 2.22761,1.32991 3.49387,1.11378c6.13943,-1.04785 12.23842,-2.27652 18.15337,-4.21915c0.93033,-0.30554 1.8602,-0.90853 3.35912,-0.31935c-4.42721,4.371 -10.54267,6.29043 -15.64176,10.99614c7.70843,-1.23582 14.47212,-2.30309 21.2292,-3.40679c17.82328,-2.91126 35.72615,-3.52549 53.227,1.12278c22.08858,5.86681 31.92493,18.19086 32.7025,38.84647c0.3714,9.8655 -1.35781,19.45717 -5.12412,28.68239c-0.34758,0.85154 -0.25189,2.03416 -1.51905,2.36096c-0.75329,-0.28046 -0.66798,-0.90309 -0.57109,-1.38605c2.78277,-13.87253 -7.32691,-28.8385 -20.86137,-35.18748c-11.66338,-5.4713 -24.11484,-6.50203 -36.82869,-5.94839c-2.55503,0.11126 -4.96221,1.06413 -6.84499,2.87276c-0.78731,0.75631 -2.00283,1.37043 -1.49261,2.70757c0.55809,1.46278 1.90095,1.79738 3.37589,1.79963c4.85716,0.00749 9.69855,0.22088 14.54634,0.57607c5.19309,0.3805 10.28549,1.29686 15.41486,2.03609c2.61218,0.37645 3.82701,1.69418 4.39018,4.17554c2.99599,13.19983 3.61588,26.48598 2.34551,39.9181c-1.91832,20.28335 -7.86013,39.4325 -18.09004,57.28093c-13.79279,24.06473 -32.61867,43.80362 -56.8145,58.91863c-23.71993,14.81772 -49.84259,23.00846 -77.91823,25.22371c-16.9441,1.33688 -33.93952,0.54546 -50.58062,-3.60051c-2.77089,-0.69038 -3.99889,-1.67904 -3.98935,-4.61937c0.09991,-30.77581 0.08837,-61.55222 -0.01275,-92.32806c-0.01036,-3.15585 1.30683,-3.88367 4.34054,-3.8664c16.65584,0.09492 33.31344,0.13099 49.96894,0.00696c17.16128,-0.12781 33.87558,-2.74267 49.34399,-10.09566c16.47092,-7.82957 27.7247,-20.12804 31.80564,-37.42151c4.21667,-17.86865 -0.50632,-33.70965 -13.68112,-47.17009c-13.18772,-13.47356 -29.97561,-20.96952 -48.14135,-26.22629c-15.2987,-4.42709 -31.01468,-6.68395 -46.82386,-8.60274c-23.37368,-2.83695 -46.8424,-2.05819 -70.29933,-2.04869c-3.26154,0.00133 -4.15412,1.18435 -4.14969,4.08951c0.05145,33.74342 0.01608,67.48699 -0.005,101.23051c-0.0308,49.3508 -0.06884,98.7016 -0.10324,148.0524c-0.0025,3.58932 -0.00034,7.17868 -0.00034,10.59938c-1.48493,0.3532 -1.94111,-0.21814 -2.38454,-0.68945c-5.00885,-5.3242 -9.98511,-10.67606 -15.00348,-15.99209c-1.54914,-1.64101 -2.18918,-3.47262 -2.18359,-5.6989c0.04215,-16.79659 -0.01703,-33.59339 -0.01468,-50.39015c0.00845,-60.22298 0.03132,-120.44601 0.03781,-180.66901c0.00038,-3.52709 -1.9021Line truncated
<path d="m229.84503,206.59113c6.99462,0.72321 13.53044,1.93892 19.73956,4.49609c15.35907,6.32553 21.74434,22.48422 13.76093,35.401c-4.75159,7.68791 -12.73685,10.64969 -21.48228,11.5909c-15.06821,1.62177 -30.22767,0.40924 -45.34196,0.76026c-3.11606,0.07234 -3.26935,-1.75847 -3.27084,-3.85943c-0.00595,-8.45132 0.00452,-16.90265 0.00068,-25.35396c-0.00305,-6.69524 0.08813,-13.39285 -0.07924,-20.08453c-0.06867,-2.74535 1.05058,-3.70261 3.81916,-3.70689c10.85401,-0.01675 21.70274,0.08864 32.85399,0.75655z" fill="#000000"/>
<path d="m282.21215,100.3525c-15.38267,7.15418 -30.52002,14.22641 -46.93939,18.35691c-12.30213,3.09474 -24.78459,5.08055 -37.44962,6.30041c-24.56242,2.36577 -49.15344,4.69592 -72.87658,11.77145c-3.49354,1.04195 -6.88905,2.38058 -10.71988,3.7181c0.45695,-1.69843 1.81201,-1.96445 2.74056,-2.58461c16.23354,-10.84139 34.72475,-16.68972 53.50751,-21.95489c17.49937,-4.90545 35.46058,-8.0016 53.06291,-12.50554c20.30459,-5.19537 39.49161,-12.8829 57.89835,-22.47692c9.71249,-5.06236 19.35956,-10.32271 30.27985,-12.8522c2.75477,-0.6381 5.43732,-0.67889 8.18997,0.10948c7.83945,2.24525 15.04097,5.55906 21.19599,10.79712c2.07243,1.76364 2.04071,2.97005 -0.60951,4.02733c-2.12898,0.84932 -4.24336,1.75144 -6.28559,2.77217c-2.29666,1.14787 -4.2201,2.35024 -6.31329,-0.65135c-1.08059,-1.54959 -3.48125,-1.19215 -5.50361,-0.63479c-13.92662,3.8382 -27.19241,9.17817 -40.17768,15.80733z" fill="#000000"/>
<path d="m303.23653,101.84625c-12.24777,6.44346 -24.41511,12.46709 -37.93186,15.78486c11.59009,-7.30627 23.11648,-14.65292 34.35762,-22.6849c1.64495,2.75157 -1.86507,3.44937 -1.32185,5.56791c9.97005,-2.78017 17.57804,-10.54646 28.21801,-11.64291c-7.15454,5.20986 -15.53551,8.37102 -23.32193,12.97504z" fill="#000000"/>
<path d="m372.47644,118.37458c2.82984,-0.09681 5.41503,-0.73071 8.77025,-0.08303c-3.05949,1.79799 -5.64247,2.71319 -8.52636,2.46522c-2.39342,-0.20581 -2.28603,-1.14943 -0.24388,-2.38219z" fill="#000000"/>
<path d="m366.29197,165.61234c2.44366,0.085 4.3998,-2.02498 6.76395,-0.38196c-4.13084,0.53 -7.54292,3.68217 -12.74783,2.84461c1.93293,-1.76933 3.93995,-1.85941 5.98388,-2.46265z" fill="#000000"/>
<path d="m119.80217,143.18391c2.81192,-1.5196 5.24274,-2.16314 8.20009,-1.99334c-2.16116,2.93811 -5.14566,1.59139 -7.90467,1.96997c-0.31314,0.00404 -0.29929,0.01658 -0.29542,0.02337z" fill="#000000"/>
</g>
<rect id="svg_3" height="1" width="0" y="118" x="-192" stroke="#000" fill="#fff"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 637 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 212 KiB

After

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 226 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 194 KiB

+1 -1
View File
@@ -1 +1 @@
Paperize is a dynamic wallpaper changer application designed to keep your device's aesthetic fresh and exciting
Paperize is an efficient wallpaper changer application with a clean design
+1
View File
@@ -0,0 +1 @@
Paperize - A Wallpaper Changer
+1
View File
@@ -0,0 +1 @@
https://youtu.be/oQCAjHB2sIo