Changed to foreground service to improve reliability

This commit is contained in:
Anthonyy232 committed 2024-04-26 10:36:45 -07:00
1 parent 37858a3e5c
commit 71b57b9f8c
19 files changed
+366 -198

No files matched your search

+1 -1
View File
@@ -15,7 +15,7 @@
</deviceKey>
</Target>
</runningDeviceTargetSelectedWithDropDown>
<timeTargetWasSelectedWithDropDown value="2024-04-23T03:07:04.964035600Z" />
<timeTargetWasSelectedWithDropDown value="2024-04-24T06:32:43.708081Z" />
</State>
</entry>
</value>
+10 -2
View File
@@ -6,8 +6,10 @@
android:name="android.software.paperize"
android:required="true" />
<uses-permission android:name="android.permission.SCHEDULE_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" />
<application
android:allowBackup="true"
@@ -32,6 +34,12 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".feature.wallpaper.alarmmanager.WallpaperReceiver" />
<service android:name=".feature.wallpaper.wallpaperservice.WallpaperService" android:foregroundServiceType="mediaPlayback"/>
<receiver android:name=".feature.wallpaper.wallpaperservice.WallpaperBootReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
@@ -1,6 +1,10 @@
package com.anthonyla.paperize
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import dagger.hilt.android.HiltAndroidApp
/**
@@ -10,5 +14,8 @@ import dagger.hilt.android.HiltAndroidApp
class App: Application() {
override fun onCreate() {
super.onCreate()
val channel = NotificationChannel("wallpaper_service_channel", "Paperize", NotificationManager.IMPORTANCE_NONE)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
@@ -7,4 +7,6 @@ object SettingsConstants {
const val SETTINGS_DATASTORE = "settings_datastore"
const val DARK_MODE_TYPE = "dark_mode_type"
const val DYNAMIC_THEME_TYPE = "dynamic_theme_type"
const val WALLPAPER_CHANGE_INTERVAL = "wallpaper_change_interval"
const val WALLPAPER_CHANGE_INTERVAL_DEFAULT = 30
}
@@ -6,9 +6,12 @@ package com.anthonyla.paperize.data.settings
interface SettingsDataStore {
suspend fun putBoolean(key: String, value: Boolean)
suspend fun putString(key: String, value: String)
suspend fun putInt(key: String, value: Int)
suspend fun getBoolean(key: String): Boolean?
suspend fun getString(key: String): String?
suspend fun getInt(key: String): Int?
suspend fun deleteBoolean(key: String)
suspend fun deleteString(key: String)
suspend fun deleteInt(key: String)
suspend fun clearPreferences()
}
@@ -27,6 +27,13 @@ class SettingsDataStoreImpl @Inject constructor (private val context: Context):
}
}
override suspend fun putInt(key: String, value: Int) {
val preferencesKey = stringPreferencesKey(key)
context.dataStore.edit {
it[preferencesKey] = value.toString()
}
}
override suspend fun getBoolean(key: String): Boolean? {
val head = context.dataStore.data.first()
val preferencesKey = booleanPreferencesKey(key)
@@ -44,6 +51,17 @@ class SettingsDataStoreImpl @Inject constructor (private val context: Context):
}
}
override suspend fun getInt(key: String): Int? {
return try {
val head = context.dataStore.data.first()
val preferencesKey = stringPreferencesKey(key)
head[preferencesKey]?.toInt()
} catch (exception: Exception) {
exception.printStackTrace()
null
}
}
override suspend fun deleteBoolean(key: String) {
val preferencesKey = booleanPreferencesKey(key)
context.dataStore.edit {
@@ -62,6 +80,15 @@ class SettingsDataStoreImpl @Inject constructor (private val context: Context):
}
}
override suspend fun deleteInt(key: String) {
val preferencesKey = stringPreferencesKey(key)
context.dataStore.edit {
if (it.contains(preferencesKey)) {
it.remove(preferencesKey)
}
}
}
override suspend fun clearPreferences() {
context.dataStore.edit {
it.clear()
@@ -75,6 +75,7 @@ object AppModule {
): SettingsDataStore = SettingsDataStoreImpl(context)
@Provides
@Singleton
fun provideContext(
@ApplicationContext context: Context,
): Context { return context }
@@ -1,103 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.alarmmanager
import android.app.WallpaperManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.core.net.toUri
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.io.IOException
import javax.inject.Inject
@AndroidEntryPoint
class WallpaperReceiver: BroadcastReceiver() {
@Inject lateinit var repository: SelectedAlbumRepository
@Inject lateinit var wallpaperScheduler: WallpaperScheduler
override fun onReceive(context: Context?, intent: Intent?) {
val defaultInterval = 15L
val timeInMinutes = intent?.getLongExtra("timeInMinutes", defaultInterval) ?: defaultInterval
if (context != null) {
CoroutineScope(Dispatchers.IO).launch {
Log.d("WallpaperReceiver", "Changing wallpaper")
changeWallpaper(context)
wallpaperScheduler.scheduleWallpaperChanger(timeInMinutes, false)
}
}
}
/**
* 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) {
val album = repository.getSelectedAlbum().first().firstOrNull()
album?.let {
var wallpaper = it.album.wallpapersInQueue.firstOrNull()
if (wallpaper != null) {
setWallpaper(context, wallpaper.toUri())
Log.d("WallpaperReceiver", "Count: ${it.album.wallpapersInQueue.size}")
/*
repository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = it.album.wallpapersInQueue.drop(1)
)
)
)
*/
}
/*
else {
val newWallpaperInQueue = it.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpaperInQueue.firstOrNull()
if (wallpaper != null) {
setWallpaper(context, wallpaper.toUri())
Log.d("WallpaperReceiver", "Count before: ${it.album.wallpapersInQueue.size}")
repository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = newWallpaperInQueue.drop(1)
)
)
)
Log.d("WallpaperReceiver", "Count after: ${it.album.wallpapersInQueue.size}")
}
}
*/
}
}
private fun setWallpaper(context: Context, wallpaper: Uri) {
val wallpaperManager = WallpaperManager.getInstance(context)
try {
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val source = ImageDecoder.createSource(
context.contentResolver,
wallpaper
)
ImageDecoder.decodeBitmap(source)
} else {
context.contentResolver.openInputStream(wallpaper)
?.use { inputStream ->
BitmapFactory.decodeStream(inputStream)
}
}
bitmap?.let { image -> wallpaperManager.setBitmap(image) }
} catch (e: IOException) {
Log.e("WallpaperReceiver", "Error changing wallpaper", e)
}
}
}
@@ -1,71 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.alarmmanager
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class WallpaperScheduler @Inject constructor (
private val context: Context
) {
private val alarmManager = context.getSystemService(AlarmManager::class.java)
private val requestCode = "Paperize".hashCode()
fun scheduleWallpaperChanger(timeInMinutes: Long, activateImmediately: Boolean = true) {
val intervalInMillis = TimeUnit.MINUTES.toMillis(timeInMinutes)
val intent = Intent(context, WallpaperReceiver::class.java).apply {
putExtra("timeInMinutes", timeInMinutes)
}
if (activateImmediately) {
context.sendBroadcast(intent)
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (alarmManager.canScheduleExactAlarms()) {
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + intervalInMillis,
PendingIntent.getBroadcast(
context,
requestCode,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
Log.d("WallpaperReceiver", "Scheduled wallpaper changer in ${TimeUnit.MILLISECONDS.toMinutes(intervalInMillis)} minutes")
} else {
// Handle the case where the app cannot schedule exact alarms
Log.e("WallpaperReceiver", "Cannot schedule exact alarms")
cancelWallpaperChanger()
}
} else {
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + intervalInMillis,
PendingIntent.getBroadcast(
context,
requestCode,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
Log.d("WallpaperReceiver", "Scheduled wallpaper changer in ${TimeUnit.MILLISECONDS.toMinutes(intervalInMillis)} minutes")
}
}
fun cancelWallpaperChanger() {
alarmManager.cancel(
PendingIntent.getBroadcast(
context,
requestCode,
Intent(context, WallpaperReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
Log.d("WallpaperReceiver", "Cancelled wallpaper changer")
}
}
@@ -18,5 +18,5 @@ data class Album(
val displayedAlbumName: String,
val coverUri: String?,
val initialized: Boolean = false,
val wallpapersInQueue: List<String> = emptyList()
val wallpapersInQueue: List<String> = emptyList(),
)
@@ -1,4 +1,7 @@
package com.anthonyla.paperize.feature.wallpaper.presentation
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
@@ -14,31 +17,38 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.core.app.ActivityCompat
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.anthonyla.paperize.feature.wallpaper.alarmmanager.WallpaperScheduler
import com.anthonyla.paperize.core.SettingsConstants
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
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsViewModel
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.wallpaperservice.WallpaperService
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val albumsViewModel: AlbumsViewModel by viewModels()
private val settingsViewModel: SettingsViewModel by viewModels()
private val wallpaperScreenViewModel: WallpaperScreenViewModel by viewModels()
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
override fun onCreate(savedInstanceState: Bundle?) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), 0)
}
enableEdgeToEdge()
// Show splash screen until app data is fully loaded and ready to be displayed
val splashScreen = installSplashScreen()
super.onCreate(savedInstanceState)
val wallpaperScheduler = WallpaperScheduler(this)
splashScreen.setKeepOnScreenCondition {
settingsViewModel.shouldNotBypassSplashScreen
|| albumsViewModel.shouldNotBypassSplashScreen
@@ -51,12 +61,20 @@ class MainActivity : ComponentActivity() {
if (lifecycleEvent == Lifecycle.Event.ON_RESUME) {
albumsViewModel.onEvent(AlbumsEvent.RefreshAlbums)
wallpaperScreenViewModel.onEvent(WallpaperEvent.Refresh)
if (!WallpaperService.isRunning && wallpaperScreenViewModel.state.value.selectedAlbum != null) {
val timeInMinutes = settingsDataStoreImpl.getInt("wallpaper_change_interval") ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val intent = Intent(this@MainActivity, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes", timeInMinutes)
}
this@MainActivity.startForegroundService(intent)
}
}
}
PaperizeTheme(settingsViewModel.state) {
Surface(tonalElevation = 5.dp) {
PaperizeApp(albumsViewModel, settingsViewModel, wallpaperScreenViewModel, wallpaperScheduler)
PaperizeApp(albumsViewModel, settingsViewModel, wallpaperScreenViewModel)
}
}
}
@@ -1,5 +1,12 @@
package com.anthonyla.paperize.feature.wallpaper.presentation
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.layout.navigationBarsPadding
@@ -18,7 +25,7 @@ import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.anthonyla.paperize.data.Contact
import com.anthonyla.paperize.feature.wallpaper.alarmmanager.WallpaperScheduler
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.presentation.add_album_screen.AddAlbumScreen
@@ -34,6 +41,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.wallpaperservice.WallpaperService
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
@@ -46,11 +54,11 @@ fun PaperizeApp(
albumsViewModel: AlbumsViewModel,
settingsViewModel: SettingsViewModel,
wallpaperScreenViewModel: WallpaperScreenViewModel,
wallpaperScheduler: WallpaperScheduler
) {
val navController = rememberNavController()
val albumState = albumsViewModel.state.collectAsStateWithLifecycle()
val selectedState = wallpaperScreenViewModel.state.collectAsStateWithLifecycle()
val context = LocalContext.current
// React to albumState changes and change selectedAlbum's details to keep it from being stale
LaunchedEffect(albumState.value.albumsWithWallpapers) {
@@ -88,11 +96,14 @@ fun PaperizeApp(
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(newSelectedAlbum))
}
?: run {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
wallpaperScheduler.cancelWallpaperChanger()
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
Intent(context, WallpaperService::class.java).also {
it.action = WallpaperService.Actions.STOP.toString()
context.startForegroundService(it)
}
}
}
}
}
// Contact author popup with email
var toContact by rememberSaveable { mutableStateOf(false) }
@@ -120,8 +131,12 @@ fun PaperizeApp(
navController.navigate("${NavScreens.AlbumView.route}/$it")
},
onScheduleWallpaperChanger = { timeInMinutes ->
wallpaperScheduler.cancelWallpaperChanger()
wallpaperScheduler.scheduleWallpaperChanger(timeInMinutes, true)
settingsViewModel.onEvent(SettingsEvent.SetWallpaperInterval(timeInMinutes))
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes", timeInMinutes)
}
context.startForegroundService(intent)
}
)
}
@@ -38,7 +38,7 @@ fun HomeScreen(
onContactClick: () -> Unit,
navigateToAddWallpaperScreen: (String) -> Unit,
onAlbumViewClick: (String) -> Unit,
onScheduleWallpaperChanger: (Long) -> Unit
onScheduleWallpaperChanger: (Int) -> Unit
) {
var tabIndex by rememberSaveable { mutableIntStateOf(0) }
val pagerState = rememberPagerState { tabItems.size }
@@ -3,6 +3,8 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen
sealed class SettingsEvent {
data object RefreshUiState: SettingsEvent()
data object RefreshWallpaperState: SettingsEvent()
data class SetDarkMode(val darkMode: Boolean?): SettingsEvent()
data class SetDynamicTheming(val dynamicTheming: Boolean): SettingsEvent()
data class SetWallpaperInterval(val interval: Int): SettingsEvent()
}
@@ -1,7 +1,9 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen
import com.anthonyla.paperize.core.SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
data class SettingsState (
val darkMode: Boolean? = null,
val dynamicTheming: Boolean = false,
val loaded: Boolean = false
val loaded: Boolean = false,
val interval: Int = WALLPAPER_CHANGE_INTERVAL_DEFAULT,
)
@@ -37,11 +37,13 @@ class SettingsViewModel @Inject constructor (
currentGetJob = async {
val darkMode = settingsDataStoreImpl.getBoolean(SettingsConstants.DARK_MODE_TYPE)
val dynamicTheming = settingsDataStoreImpl.getBoolean(SettingsConstants.DYNAMIC_THEME_TYPE) ?: false
val wallpaperInterval = settingsDataStoreImpl.getInt(SettingsConstants.WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
_state.update { it.copy(
darkMode = darkMode,
dynamicTheming = dynamicTheming,
loaded = true
loaded = true,
interval = wallpaperInterval
) }
if (_state.value.loaded) {
@@ -51,9 +53,6 @@ class SettingsViewModel @Inject constructor (
}
}
fun onEvent(event: SettingsEvent) {
when (event) {
is SettingsEvent.RefreshUiState -> {
@@ -65,7 +64,7 @@ class SettingsViewModel @Inject constructor (
dynamicTheming = when(settingsDataStoreImpl.getBoolean(SettingsConstants.DYNAMIC_THEME_TYPE)) {
true -> true
false, null -> false
},
}
) }
}
}
@@ -89,6 +88,22 @@ class SettingsViewModel @Inject constructor (
refreshSettings()
}
}
is SettingsEvent.SetWallpaperInterval -> {
viewModelScope.launch {
settingsDataStoreImpl.putInt(SettingsConstants.WALLPAPER_CHANGE_INTERVAL, event.interval)
refreshSettings()
}
}
is SettingsEvent.RefreshWallpaperState -> {
viewModelScope.launch {
currentGetJob?.cancel()
currentGetJob = viewModelScope.launch {
_state.update { it.copy(
interval = settingsDataStoreImpl.getInt(SettingsConstants.WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
) }
}
}
}
}
}
@@ -101,6 +116,7 @@ class SettingsViewModel @Inject constructor (
true -> true
false, null -> false
},
interval = settingsDataStoreImpl.getInt(SettingsConstants.WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
) }
}
}
@@ -7,9 +7,15 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Snackbar
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -25,12 +31,13 @@ import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
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.launch
@Composable
fun WallpaperScreen(
albumsViewModel: AlbumsViewModel = hiltViewModel(),
wallpaperScreenViewModel: WallpaperScreenViewModel = hiltViewModel(),
onScheduleWallpaperChanger: (Long) -> Unit
onScheduleWallpaperChanger: (Int) -> Unit
) {
val context = LocalContext.current
val albumState = albumsViewModel.state.collectAsStateWithLifecycle()
@@ -77,12 +84,12 @@ fun WallpaperScreen(
wallpapers = wallpapers
)
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(newSelectedAlbum))
onScheduleWallpaperChanger(15)
onScheduleWallpaperChanger(1)
openBottomSheet = false
}
)
}
}
}
},
)
}
@@ -0,0 +1,26 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaperservice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsViewModel
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) {
Log.d("PaperizeWallpaperChanger", "Boot completed")
val serviceIntent = Intent(context, WallpaperService::class.java)
serviceIntent.action = WallpaperService.Actions.START.toString()
val timeInMinutes = runBlocking { settingsDataStoreImpl.getInt(SettingsConstants.WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT }
serviceIntent.putExtra("timeInMinutes", timeInMinutes)
context.startForegroundService(serviceIntent);
}
}
}
@@ -0,0 +1,208 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaperservice
import android.app.Notification
import android.app.NotificationManager
import android.app.Service
import android.app.WallpaperManager
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import java.io.IOException
import javax.inject.Inject
@AndroidEntryPoint
class WallpaperService: Service() {
@Inject lateinit var repository: SelectedAlbumRepository
private val handler = Handler(Looper.getMainLooper())
private lateinit var runnableCode: Runnable
private var timeInMinutes: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
companion object {
var isRunning = false
}
enum class Actions {
START,
STOP
}
override fun onBind(p0: Intent?): IBinder? {
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(0, 0))
isRunning = true
runnableCode = object : Runnable {
override fun run() {
Log.d("PaperizeWallpaperChanger", "Scheduled in: $timeInMinutes")
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
changeWallpaper(this@WallpaperService)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler.postDelayed(self, timeInMinutes * 60 * 1000L)
}
}
}
}
}
/**
* Start the service and schedule the wallpaper change
*/
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
isRunning = true
when(intent?.action) {
Actions.START.toString() -> {
timeInMinutes = intent.getIntExtra("timeInMinutes", 1)
// Schedule the next wallpaper change
runnableCode = object : Runnable {
override fun run() {
Log.d("PaperizeWallpaperChanger", "Scheduled in: $timeInMinutes")
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
changeWallpaper(this@WallpaperService)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler.postDelayed(self, timeInMinutes * 60 * 1000L)
}
}
}
}
handler.post(runnableCode)
}
Actions.STOP.toString() -> {
handler.removeCallbacks(runnableCode)
stopSelf()
}
}
return START_STICKY
}
/**
* Clean up the service when it is destroyed
*/
override fun onDestroy() {
Log.d("PaperizeWallpaperChanger", "Service destroyed")
super.onDestroy()
isRunning = false
handler.removeCallbacks(runnableCode)
}
/**
* Restart the service if it is removed
override fun onTaskRemoved(rootIntent: Intent?) {
Log.d("PaperizeWallpaperChanger", "Service removed by swipe")
isRunning = false
handler.removeCallbacks(runnableCode)
val restartServiceIntent = Intent(applicationContext, this::class.java).apply {
action = Actions.START.toString()
putExtra("timeInMinutes", timeInMinutes)
}
restartServiceIntent.setPackage(packageName)
applicationContext.startForegroundService(restartServiceIntent)
super.onTaskRemoved(rootIntent)
} */
/**
* Creates a notification for the wallpaper service
*/
private fun createNotification(current: Int = 0, total: Int = 0): Notification {
return NotificationCompat.Builder(this, "wallpaper_service_channel")
.setContentTitle("Paperize")
.setContentText("Changing wallpaper... Album: $current/$total")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.build()
}
/**
* 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) {
val album = repository.getSelectedAlbum().first().firstOrNull()
album?.let {
val notification = createNotification(it.album.wallpapersInQueue.size, it.wallpapers.size)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
var wallpaper = it.album.wallpapersInQueue.firstOrNull()
if (wallpaper != null) {
setWallpaper(context, wallpaper.toUri())
repository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = it.album.wallpapersInQueue.drop(1)
)
)
)
}
else {
val newWallpaperInQueue = it.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpaperInQueue.firstOrNull()
if (wallpaper != null) {
setWallpaper(context, wallpaper.toUri())
repository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = newWallpaperInQueue.drop(1)
)
)
)
}
}
}
}
/**
* Sets the wallpaper to the given uri
*/
private fun setWallpaper(context: Context, wallpaper: Uri) {
val wallpaperManager = WallpaperManager.getInstance(context)
try {
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val source = ImageDecoder.createSource(context.contentResolver, wallpaper)
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
val displayMetrics = context.resources.displayMetrics
val targetWidth = displayMetrics.widthPixels
val targetHeight = displayMetrics.heightPixels
decoder.setTargetSize(targetWidth, targetHeight)
}
} else {
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
BitmapFactory.decodeStream(inputStream)
}
}
bitmap?.let { image -> wallpaperManager.setBitmap(image) }
} catch (e: IOException) {
Log.e("PaperizeWallpaperChanger", "Error changing wallpaper", e)
}
}
}