Basic implementation of wallpaper changing using WorkManager. May consider swapping to foreground service to increase reliability

This commit is contained in:
Anthonyy232 committed 2024-04-22 16:58:47 -07:00
1 parent 0f975c9b20
commit 0bca639e3a
32 files changed
+377 -127

No files matched your search

+1 -1
View File
@@ -15,7 +15,7 @@
</deviceKey>
</Target>
</runningDeviceTargetSelectedWithDropDown>
<timeTargetWasSelectedWithDropDown value="2024-04-04T19:54:45.940456200Z" />
<timeTargetWasSelectedWithDropDown value="2024-04-08T04:25:59.382027900Z" />
</State>
</entry>
</value>
-1
View File
@@ -1,4 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="NullableNotNullManager">
+17 -15
View File
@@ -57,34 +57,36 @@ androidComponents {
}
dependencies {
implementation("androidx.core:core-ktx:1.12.0")
implementation("androidx.core:core-ktx:1.13.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0")
implementation("androidx.activity:activity-compose:1.8.2")
implementation(platform("androidx.compose:compose-bom:2024.04.00"))
implementation("androidx.compose.ui:ui:1.6.5")
implementation("androidx.compose.ui:ui-graphics:1.6.5")
implementation("androidx.compose.ui:ui-tooling-preview:1.6.5")
implementation("androidx.activity:activity-compose:1.9.0")
implementation(platform("androidx.compose:compose-bom:2024.04.01"))
implementation("androidx.compose.ui:ui:1.6.6")
implementation("androidx.compose.ui:ui-graphics:1.6.6")
implementation("androidx.compose.ui:ui-tooling-preview:1.6.6")
implementation("androidx.compose.material3:material3:1.2.1")
implementation("androidx.navigation:navigation-compose:2.7.7")
implementation("androidx.compose.material:material:1.6.5")
implementation("androidx.datastore:datastore:1.1.0-rc01")
implementation("androidx.datastore:datastore-preferences:1.1.0-rc01")
implementation("androidx.compose.material:material-icons-extended:1.6.5")
implementation("androidx.compose.material:material:1.6.6")
implementation("androidx.datastore:datastore:1.1.0")
implementation("androidx.datastore:datastore-preferences:1.1.0")
implementation("androidx.compose.material:material-icons-extended:1.6.6")
implementation("com.google.accompanist:accompanist-adaptive:0.34.0")
implementation("androidx.hilt:hilt-navigation-compose:1.2.0")
implementation("androidx.compose.animation:animation:1.6.5")
implementation("androidx.compose.animation:animation:1.6.6")
implementation("androidx.core:core-splashscreen:1.1.0-rc01")
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.7.0")
implementation("com.google.code.gson:gson:2.10.1")
implementation("androidx.documentfile:documentfile:1.1.0-alpha01")
implementation("net.engawapg.lib:zoomable:1.6.1")
implementation("com.github.skydoves:landscapist-glide:2.3.2")
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")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.6.0-alpha03")
androidTestImplementation("androidx.compose.ui:ui-test-junit4:1.6.5")
debugImplementation("androidx.compose.ui:ui-tooling:1.6.5")
debugImplementation("androidx.compose.ui:ui-test-manifest:1.6.5")
androidTestImplementation("androidx.compose.ui:ui-test-junit4:1.6.6")
debugImplementation("androidx.compose.ui:ui-tooling:1.6.6")
debugImplementation("androidx.compose.ui:ui-test-manifest:1.6.6")
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")
@@ -1,24 +0,0 @@
package com.anthonyla.paperize
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.anthonyla.paperize", appContext.packageName)
}
}
+6 -12
View File
@@ -5,6 +5,8 @@
<uses-feature
android:name="android.software.paperize"
android:required="true" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<application
android:allowBackup="true"
@@ -31,17 +33,9 @@
</intent-filter>
</activity>
<service
android:name=".data.configuration.PaperizeWallpaperService"
android:enabled="true"
android:permission="android.permission.BIND_WALLPAPER"
android:exported="true">
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<meta-data
android:name="android.service.wallpaper"
android:resource="@xml/paperize" />
</service>
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
tools:node="remove" />
</application>
</manifest>
@@ -1,11 +1,21 @@
package com.anthonyla.paperize
import android.app.Application
import android.util.Log
import androidx.work.Configuration
import com.anthonyla.paperize.feature.wallpaper.workmanager.WallpaperWorkerFactory
import dagger.hilt.android.HiltAndroidApp
import javax.inject.Inject
/**
* Application class for Hilt
*/
@HiltAndroidApp
class App: Application() {
class App: Application(), Configuration.Provider {
@Inject lateinit var workerFactory: WallpaperWorkerFactory
override val workManagerConfiguration: Configuration
get() = Configuration.Builder()
.setMinimumLoggingLevel(Log.DEBUG)
.setWorkerFactory(workerFactory)
.build()
}
@@ -2,7 +2,9 @@ package com.anthonyla.paperize.di
import android.app.Application
import android.content.Context
import androidx.hilt.work.HiltWorkerFactory
import androidx.room.Room
import androidx.work.WorkerFactory
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.data.settings.SettingsDataStoreImpl
import com.anthonyla.paperize.feature.wallpaper.data.data_source.AlbumDatabase
@@ -11,6 +13,7 @@ import com.anthonyla.paperize.feature.wallpaper.data.repository.AlbumRepositoryI
import com.anthonyla.paperize.feature.wallpaper.data.repository.SelectedAlbumRepositoryImpl
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
import com.anthonyla.paperize.feature.wallpaper.workmanager.WallpaperWorkerFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
@@ -2,6 +2,7 @@ package com.anthonyla.paperize.feature.wallpaper.data.data_source
import androidx.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
/**
* Converters for Room database to convert list of strings to json string and vice versa
@@ -20,4 +21,18 @@ class Converters {
*/
@TypeConverter
fun jsonStringToList(value: String) = gson.fromJson(value, Array<String>::class.java).toList()
@TypeConverter
fun fromPairList(value: List<Pair<String, Boolean>>): String {
val gson = Gson()
val type = object : TypeToken<List<Pair<String, Boolean>>>() {}.type
return gson.toJson(value, type)
}
@TypeConverter
fun toPairList(value: String): List<Pair<String, Boolean>> {
val gson = Gson()
val type = object : TypeToken<List<Pair<String, Boolean>>>() {}.type
return gson.fromJson(value, type)
}
}
@@ -22,6 +22,15 @@ interface SelectedAlbumDao {
@Query("SELECT * FROM album")
fun getSelectedAlbum(): Flow<List<SelectedAlbum>>
@Query("SELECT * FROM wallpaper WHERE isInRotation = 1")
fun getWallpapersInRotation(): Flow<List<Wallpaper>>
@Query("SELECT * FROM wallpaper ORDER BY RANDOM() LIMIT 1")
fun getRandomWallpaperInRotation(): Wallpaper?
@Query("UPDATE wallpaper SET isInRotation = 1")
suspend fun setAllWallpapersInRotation()
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAlbum(album: Album)
@@ -42,6 +51,7 @@ interface SelectedAlbumDao {
@Query("DELETE FROM album")
suspend fun deleteAllAlbums()
@Query("DELETE FROM wallpaper")
suspend fun deleteAllWallpapers()
@@ -16,6 +16,18 @@ class SelectedAlbumRepositoryImpl(
return dao.getSelectedAlbum()
}
override fun getWallpapersInRotation(): Flow<List<Wallpaper>> {
return dao.getWallpapersInRotation()
}
override fun getRandomWallpaperInRotation(): Wallpaper? {
return dao.getRandomWallpaperInRotation()
}
override suspend fun setAllWallpapersInRotation() {
dao.setAllWallpapersInRotation()
}
override suspend fun upsertSelectedAlbum(selectedAlbum: SelectedAlbum) {
dao.upsertAlbum(selectedAlbum.album)
dao.upsertWallpaperList(selectedAlbum.wallpapers)
@@ -15,4 +15,5 @@ data class Album(
@PrimaryKey(autoGenerate = false) val initialAlbumName: String,
val displayedAlbumName: String,
val coverUri: String?,
val initialized: Boolean = false
)
@@ -9,7 +9,7 @@ import androidx.room.PrimaryKey
* @param initialAlbumName The initial album name.
* @param folderName The folder name.
* @param coverUri The cover URI.
* @param wallpapers The list of wallpaper URI strings.
* @param wallpapers The list of wallpaper URI strings paired with inRotation boolean as a <Pair>
* @param folderUri The folder directory URI.
*/
@Entity
@@ -17,7 +17,7 @@ data class Folder(
val initialAlbumName: String,
val folderName: String?,
val coverUri: String?,
val wallpapers: List<String> = emptyList(),
val wallpapers: List<Pair<String, Boolean>> = emptyList(),
val folderUri: String,
@PrimaryKey(autoGenerate = false) val key: Int
)
@@ -8,10 +8,12 @@ import androidx.room.PrimaryKey
*
* @param initialAlbumName The name of the album the wallpaper belongs to.
* @param wallpaperUri The URI of the wallpaper.
* @param isInRotation Whether the wallpaper is in rotation.
*/
@Entity
data class Wallpaper(
val initialAlbumName: String,
val wallpaperUri: String,
val isInRotation: Boolean,
@PrimaryKey(autoGenerate = false) val key: Int
)
@@ -11,6 +11,21 @@ interface SelectedAlbumRepository {
*/
fun getSelectedAlbum(): Flow<List<SelectedAlbum>>
/**
* Get wallpapers in rotation from database
*/
fun getWallpapersInRotation(): Flow<List<Wallpaper>>
/**
* Get random wallpaper in rotation
*/
fun getRandomWallpaperInRotation(): Wallpaper?
/**
* Add all wallpapers back into rotation
*/
suspend fun setAllWallpapersInRotation()
/**
* Upsert or insert selectedAlbum to database with its wallpapers
*/
@@ -33,6 +33,7 @@ class MainActivity : ComponentActivity() {
private val wallpaperScreenViewModel: WallpaperScreenViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
// Show splash screen until app data is fully loaded and ready to be displayed
val splashScreen = installSplashScreen()
super.onCreate(savedInstanceState)
@@ -31,6 +31,7 @@ import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.Set
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.util.navigation.NavScreens
import com.anthonyla.paperize.feature.wallpaper.workmanager.WorkerRepository
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
@@ -42,22 +43,55 @@ import java.nio.charset.StandardCharsets
fun PaperizeApp(
albumsViewModel: AlbumsViewModel,
settingsViewModel: SettingsViewModel,
wallpaperScreenViewModel: WallpaperScreenViewModel
wallpaperScreenViewModel: WallpaperScreenViewModel,
repository: WorkerRepository
) {
val navController = rememberNavController()
val albumState = albumsViewModel.state.collectAsStateWithLifecycle()
val selectedState = wallpaperScreenViewModel.state.collectAsStateWithLifecycle()
// React to albumState changes and change selectedAlbum's details to keep it from being stale
LaunchedEffect(albumState.value.albumsWithWallpapers) {
albumState.value.albumsWithWallpapers.forEach {
if (!it.album.initialized && (it.wallpapers.isNotEmpty() || it.folders.isNotEmpty())) {
albumsViewModel.onEvent(AlbumsEvent.InitializeAlbum(it))
}
else if (it.album.initialized && it.wallpapers.isEmpty() && it.folders.isEmpty()) {
if (navController.currentDestination?.route != NavScreens.Home.route) {
navController.popBackStack(NavScreens.Home.route, false)
}
albumsViewModel.onEvent(AlbumsEvent.DeleteAlbumWithWallpapers(it))
}
}
selectedState.value.selectedAlbum?.let { selectedAlbum ->
albumState.value.albumsWithWallpapers.find { it.album.initialAlbumName == selectedAlbum.album.initialAlbumName }
?.let { foundAlbum -> wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(foundAlbum)) }
?: wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
?.let { foundAlbum -> wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(
foundAlbum.copy(
album = foundAlbum.album,
folders = foundAlbum.folders.map { folder ->
folder.copy(
wallpapers = folder.wallpapers.map { wallpaper ->
Pair(
wallpaper.first,
selectedAlbum.wallpapers.find { selectedWallpaper -> selectedWallpaper.wallpaperUri == wallpaper.first }?.isInRotation ?: true
)
}
)
},
wallpapers = foundAlbum.wallpapers.map {
it.copy(
isInRotation = selectedAlbum.wallpapers.find { wallpaper -> wallpaper.wallpaperUri == it.wallpaperUri }?.isInRotation ?: true
)
}
)
)) } ?: run {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
repository.cancelWorker()
}
}
}
val navController = rememberNavController()
// Contact author popup with email
var toContact by rememberSaveable { mutableStateOf(false) }
if (toContact) {
@@ -73,9 +107,6 @@ fun PaperizeApp(
// Navigate to the home screen with the navbar and top bar
composable(
route = NavScreens.Home.route,
exitTransition = {
slideOutHorizontally(targetOffsetX = { fullWidth -> -fullWidth })
}
) {
HomeScreen(
onSettingsClick = { navController.navigate(NavScreens.Settings.route) },
@@ -98,7 +129,9 @@ fun PaperizeApp(
AddAlbumScreen(
initialAlbumName = it,
onBackClick = { navController.navigateUp() },
onConfirmation = { navController.navigateUp() },
onConfirmation = {
navController.navigateUp()
},
onShowWallpaperView = { wallpaper ->
val encodedWallpaper = runBlocking { encodeUri(uri = wallpaper) }
navController.navigate("${NavScreens.WallpaperView.route}/$encodedWallpaper")
@@ -173,7 +206,7 @@ fun PaperizeApp(
},
onShowFolderView = { folder, folderName, wallpapers ->
val encodedFolder = runBlocking { encodeUri(uri = folder) }
val encodedWallpapers = runBlocking { encodeUri(uri = Gson().toJson(wallpapers)) }
val encodedWallpapers = runBlocking { encodeUri(uri = Gson().toJson(wallpapers.map { it.first })) }
navController.navigate("${NavScreens.FolderView.route}/$encodedFolder/$folderName/$encodedWallpapers")
},
onDeleteAlbum = {
@@ -42,7 +42,7 @@ fun AddAlbumScreen(
onBackClick: () -> Unit,
onConfirmation: () -> Unit,
onShowWallpaperView: (String) -> Unit,
onShowFolderView: (String, String?, List<String>) -> Unit
onShowFolderView: (String, String?, List<Pair<String, Boolean>>) -> Unit
) {
val context = LocalContext.current
val lazyListState = rememberLazyStaggeredGridState()
@@ -106,7 +106,6 @@ fun AddAlbumScreen(
onConfirmationClick = {
viewModel.onEvent(AddAlbumEvent.ReflectAlbumName(it))
viewModel.onEvent(AddAlbumEvent.SaveAlbum)
viewModel.onEvent(AddAlbumEvent.ClearState)
onConfirmation()
},
onSelectAllClick = {
@@ -38,6 +38,7 @@ class AddAlbumViewModel @Inject constructor(
when (event) {
is AddAlbumEvent.SaveAlbum -> {
viewModelScope.launch {
if (_state.value.wallpapers.isEmpty() && _state.value.folders.isEmpty()) { return@launch }
val albumCoverUri = when (_state.value.isEmpty) {
true -> ""
false -> {
@@ -52,10 +53,10 @@ class AddAlbumViewModel @Inject constructor(
album = Album(
initialAlbumName = _state.value.initialAlbumName,
displayedAlbumName = _state.value.displayedAlbumName,
coverUri = albumCoverUri
coverUri = albumCoverUri,
),
wallpapers = _state.value.wallpapers,
folders = _state.value.folders
folders = _state.value.folders,
)
repository.upsertAlbumWithWallpaperAndFolder(albumWithWallpaperAndFolder)
@@ -120,7 +121,8 @@ class AddAlbumViewModel @Inject constructor(
Wallpaper(
initialAlbumName = it.initialAlbumName,
wallpaperUri = event.wallpaperUri,
key = event.wallpaperUri.hashCode() + it.initialAlbumName.hashCode()
key = event.wallpaperUri.hashCode() + it.initialAlbumName.hashCode(),
isInRotation = true
)
),
) }
@@ -133,15 +135,15 @@ class AddAlbumViewModel @Inject constructor(
if (!_state.value.folders.any { it.folderUri == event.directoryUri }) {
val wallpapers: List<String> = getWallpaperFromFolder(event.directoryUri, context)
val folderName = getFolderNameFromUri(event.directoryUri, context)
_state.update { it.copy(
folders = it.folders.plus(
_state.update { state ->
state.copy( folders = state.folders.plus(
Folder(
initialAlbumName = it.initialAlbumName,
initialAlbumName = state.initialAlbumName,
folderName = folderName,
folderUri = event.directoryUri,
coverUri = wallpapers.randomOrNull(),
wallpapers = wallpapers.ifEmpty { emptyList() },
key = event.directoryUri.hashCode() + it.initialAlbumName.hashCode()
wallpapers = wallpapers.map { it to true },
key = event.directoryUri.hashCode() + state.initialAlbumName.hashCode()
)
),
) }
@@ -12,4 +12,8 @@ sealed class AlbumsEvent {
val title: String,
val albumWithWallpaperAndFolder: AlbumWithWallpaperAndFolder
): AlbumsEvent()
data class InitializeAlbum(
val albumWithWallpaperAndFolder: AlbumWithWallpaperAndFolder
): AlbumsEvent()
}
@@ -68,6 +68,15 @@ class AlbumsViewModel @Inject constructor (
refreshAlbums()
}
}
is AlbumsEvent.InitializeAlbum -> {
viewModelScope.launch {
repository.updateAlbum(
event.albumWithWallpaperAndFolder.album.copy(
initialized = true
)
)
}
}
}
}
@@ -96,7 +105,7 @@ class AlbumsViewModel @Inject constructor (
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))
repository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers.map { it to true }))
}
}
}
@@ -166,9 +175,9 @@ class AlbumsViewModel @Inject constructor (
}
folders.forEach { folder ->
folder.wallpapers.forEach { wallpaper ->
val file = DocumentFile.fromSingleUri(context, wallpaper.toUri())
val file = DocumentFile.fromSingleUri(context, wallpaper.first.toUri())
if (file?.exists() == true) {
return wallpaper
return wallpaper.first
}
}
}
@@ -30,7 +30,7 @@ fun AlbumViewScreen(
album: AlbumWithWallpaperAndFolder,
onBackClick: () -> Unit,
onShowWallpaperView: (String) -> Unit,
onShowFolderView: (String, String?, List<String>) -> Unit,
onShowFolderView: (String, String?, List<Pair<String, Boolean>>) -> Unit,
onDeleteAlbum: () -> Unit,
onTitleChange: (String, AlbumWithWallpaperAndFolder) -> Unit,
onSelectionDeleted: () -> Unit
@@ -174,7 +174,6 @@ fun AlbumViewTopBar(
Icon(
imageVector = Icons.Outlined.Delete,
contentDescription = stringResource(R.string.select_all_images_for_deletion),
tint = Color.White.copy(alpha = 0.7f),
modifier = Modifier.padding(6.dp)
)
}
@@ -87,7 +87,7 @@ fun DarkModeListItem(darkMode: Boolean?, onDarkModeClick: (Boolean?) -> Unit) {
SingleChoiceSegmentedButtonRow(
modifier = Modifier
.weight(1f)
.width(100.dp)
.width(125.dp)
.height(36.dp)
) {
options.forEachIndexed { index, label ->
@@ -105,13 +105,9 @@ fun DarkModeListItem(darkMode: Boolean?, onDarkModeClick: (Boolean?) -> Unit) {
selected = index == selectedIndex
) {
Icon(
imageVector = if (index == selectedIndex) label.third else label.second,
contentDescription = label.first,
imageVector =
if(selectedIndex != index)
label.second
else
label.third,
modifier = Modifier.requiredSize(18.dp)
modifier = if (index != selectedIndex) Modifier.requiredSize(24.dp) else Modifier.requiredSize(12.dp)
)
}
}
@@ -1,9 +1,13 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
sealed class WallpaperEvent {
data class UpdateSelectedAlbum(val albumWithWallpaperAndFolder: AlbumWithWallpaperAndFolder): WallpaperEvent()
data class StartWallpaperWorker(val time: Long): WallpaperEvent()
data class ExitRotation(val wallpaper: Wallpaper): WallpaperEvent()
object Reset : WallpaperEvent()
object Refresh : WallpaperEvent()
object StopWallpaperWorker : WallpaperEvent()
}
@@ -1,5 +1,14 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen
import android.Manifest
import android.app.Activity
import android.app.WallpaperManager
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.os.Build
import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
@@ -11,18 +20,28 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
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.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.anthonyla.paperize.feature.wallpaper.presentation.album.AlbumsViewModel
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.AlbumBottomSheet
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.CurrentSelectedAlbum
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import java.io.IOException
@Composable
fun WallpaperScreen(
albumsViewModel: AlbumsViewModel = hiltViewModel(),
wallpaperScreenViewModel: WallpaperScreenViewModel = hiltViewModel()
) {
val context = LocalContext.current
val albumState = albumsViewModel.state.collectAsStateWithLifecycle()
val selectedState = wallpaperScreenViewModel.state.collectAsStateWithLifecycle()
var openBottomSheet by rememberSaveable { mutableStateOf(false) }
@@ -48,9 +67,14 @@ fun WallpaperScreen(
currentSelectedAlbum = selectedState.value.selectedAlbum,
onDismiss = { openBottomSheet = false },
onSelect = { album ->
if (ContextCompat.checkSelfPermission(context, Manifest.permission.SET_WALLPAPER) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context as Activity, arrayOf(Manifest.permission.SET_WALLPAPER), 0)
}
if ((selectedState.value.selectedAlbum?.album?.initialAlbumName ?: "") != album.album.initialAlbumName) {
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(album))
}
wallpaperScreenViewModel.onEvent(WallpaperEvent.StartWallpaperWorker(1))
openBottomSheet = false
}
)
@@ -58,20 +82,4 @@ fun WallpaperScreen(
}
}
)
}
/*
if (albumState.value.albumsWithWallpapers.firstOrNull() != null) {
val wallpaperManager = WallpaperManager.getInstance(context)
val inputStream = albumState.value.albumsWithWallpapers.firstOrNull()?.let {
it.album.coverUri?.let { it1 ->
context.contentResolver.openInputStream(
it1.toUri()
)
}
}
val bitmap = BitmapFactory.decodeStream(inputStream)
wallpaperManager.setBitmap(bitmap)
}
*/
}
@@ -10,6 +10,7 @@ import androidx.lifecycle.viewModelScope
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.SelectedAlbumRepository
import com.anthonyla.paperize.feature.wallpaper.workmanager.WorkerRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
@@ -22,7 +23,8 @@ import javax.inject.Inject
@HiltViewModel
class WallpaperScreenViewModel @Inject constructor (
application: Application,
private val repository: SelectedAlbumRepository
private val repository: SelectedAlbumRepository,
private val workerRepository: WorkerRepository
) : AndroidViewModel(application) {
var shouldNotBypassSplashScreen by mutableStateOf(true)
private val context: Context get() = getApplication<Application>().applicationContext
@@ -49,8 +51,9 @@ class WallpaperScreenViewModel @Inject constructor (
folder.wallpapers.map { wallpaper ->
Wallpaper(
initialAlbumName = event.albumWithWallpaperAndFolder.album.initialAlbumName,
wallpaperUri = wallpaper,
key = wallpaper.hashCode() + event.albumWithWallpaperAndFolder.album.initialAlbumName.hashCode()
wallpaperUri = wallpaper.first,
key = wallpaper.hashCode() + event.albumWithWallpaperAndFolder.album.initialAlbumName.hashCode(),
isInRotation = wallpaper.second
)
}
}
@@ -62,6 +65,17 @@ class WallpaperScreenViewModel @Inject constructor (
repository.upsertSelectedAlbum(newSelectedAlbum)
}
}
is WallpaperEvent.StartWallpaperWorker -> {
workerRepository.scheduleWallpaperChanger(event.time)
}
is WallpaperEvent.StopWallpaperWorker -> {
workerRepository.cancelWorker()
}
is WallpaperEvent.ExitRotation -> {
viewModelScope.launch {
repository.upsertWallpaper(event.wallpaper.copy(isInRotation = false))
}
}
is WallpaperEvent.Refresh -> {
refreshAlbums()
}
@@ -2,6 +2,7 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.c
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
@@ -54,6 +55,7 @@ fun AlbumBottomSheet(
onDismissRequest = { onDismiss() },
sheetState = modalBottomSheetState,
dragHandle = { BottomSheetDefaults.DragHandle() },
windowInsets = WindowInsets(0.dp)
) {
albums.forEach {
ListItem(
@@ -0,0 +1,104 @@
package com.anthonyla.paperize.feature.wallpaper.workmanager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.WallpaperManager
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.anthonyla.paperize.R
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
/**
* Worker class to change wallpaper periodically
*/
@HiltWorker
class WallpaperWorker @AssistedInject constructor(
@Assisted private val repository: SelectedAlbumRepository,
@Assisted private val appContext: Context,
@Assisted workerParams: WorkerParameters
) : CoroutineWorker(appContext, workerParams) {
companion object {
const val CHANNEL_ID = "wallpaper_worker_channel"
const val NOTIFICATION_ID = 1
}
override suspend fun doWork(): Result {
return try {
withContext(Dispatchers.IO) {
changeWallpaper(appContext)
createNotificationChannel()
showNotification()
}
Result.success()
} catch (e: Exception) {
Result.failure()
}
}
private suspend fun changeWallpaper(context: Context) {
val wallpaperManager = WallpaperManager.getInstance(context)
val wallpaper = repository.getRandomWallpaperInRotation()
if (wallpaper != null) {
try {
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val source = ImageDecoder.createSource(
context.contentResolver,
wallpaper.wallpaperUri.toUri()
)
ImageDecoder.decodeBitmap(source)
} else {
context.contentResolver.openInputStream(wallpaper.wallpaperUri.toUri())
?.use { inputStream ->
BitmapFactory.decodeStream(inputStream)
}
}
bitmap?.let { bmp ->
wallpaperManager.setBitmap(bmp)
}
repository.upsertWallpaper(wallpaper.copy(isInRotation = false))
} catch (e: IOException) {
Log.e("WallpaperWorker", "Error changing wallpaper", e)
}
}
else {
repository.setAllWallpapersInRotation()
}
}
private fun createNotificationChannel() {
val name = "Wallpaper Worker"
val descriptionText = "Notification for Wallpaper Worker"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
private fun showNotification() {
val builder = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Wallpaper Worker")
.setContentText("Wallpaper Worker is running")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
val notificationManager: NotificationManager =
applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(NOTIFICATION_ID, builder.build())
}
}
@@ -0,0 +1,24 @@
package com.anthonyla.paperize.feature.wallpaper.workmanager
import android.content.Context
import androidx.work.ListenableWorker
import androidx.work.WorkerFactory
import androidx.work.WorkerParameters
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class WallpaperWorkerFactory @Inject constructor(
private val selectedAlbumRepository: SelectedAlbumRepository
) : WorkerFactory() {
override fun createWorker(
appContext: Context,
workerClassName: String,
workerParameters: WorkerParameters
): ListenableWorker = WallpaperWorker(
selectedAlbumRepository,
appContext,
workerParameters
)
}
@@ -0,0 +1,29 @@
package com.anthonyla.paperize.feature.wallpaper.workmanager
import android.content.Context
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import java.util.concurrent.TimeUnit
import javax.inject.Inject
/**
* Repository class to handle WallpaperWorker scheduling
*/
class WorkerRepository @Inject constructor(context: Context) {
private val workManager = WorkManager.getInstance(context)
fun scheduleWallpaperChanger(time: Long) {
val workRequest = PeriodicWorkRequestBuilder<WallpaperWorker>(
15, TimeUnit.MINUTES
)
workManager.enqueueUniquePeriodicWork(
"WallpaperWorker",
ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE,
workRequest.build()
)
}
fun cancelWorker() {
workManager.cancelAllWork()
}
}
@@ -1,17 +0,0 @@
package com.anthonyla.paperize
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
+2 -2
View File
@@ -6,8 +6,8 @@ buildscript {
}
plugins {
id("com.android.application") version "8.3.1" apply false
id("com.android.library") version "8.3.1" apply false
id("com.android.application") version "8.3.2" apply false
id("com.android.library") version "8.3.2" apply false
id("org.jetbrains.kotlin.android") version "1.9.0" apply false
id("com.google.dagger.hilt.android") version "2.50" apply false
id("com.google.devtools.ksp") version "1.9.0-1.0.13" apply false