photos: add video and GIF live wallpaper support
- Commit
02be004d63d7b61909ad336af74b45bf35295d91- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-11 17:13 UTC (3 months ago)
- Parents
81256be
Diff
photos/src/main/AndroidManifest.xml
diff --git a/photos/src/main/AndroidManifest.xml b/photos/src/main/AndroidManifest.xmlindex 40ba99fbfc..7ae695320d 100644--- a/photos/src/main/AndroidManifest.xml+++ b/photos/src/main/AndroidManifest.xml@@ -95,6 +95,18 @@ android:foregroundServiceType="dataSync" tools:node="merge" /> + <service+ android:name=".service.LiveWallpaperService"+ android:exported="true"+ android:permission="android.permission.BIND_WALLPAPER">+ <intent-filter>+ <action android:name="android.service.wallpaper.WallpaperService" />+ </intent-filter>+ <meta-data+ android:name="android.service.wallpaper"+ android:resource="@xml/live_wallpaper" />+ </service>+ </application> </manifest>\ No newline at end of file
photos/src/main/java/com/vayunmathur/photos/service/LiveWallpaperService.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/service/LiveWallpaperService.kt b/photos/src/main/java/com/vayunmathur/photos/service/LiveWallpaperService.ktnew file mode 100644index 0000000000..404d6c4141--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/service/LiveWallpaperService.kt@@ -0,0 +1,197 @@+package com.vayunmathur.photos.service++import android.graphics.Color+import android.graphics.ImageDecoder+import android.graphics.drawable.AnimatedImageDrawable+import android.graphics.drawable.Drawable+import android.net.Uri+import android.service.wallpaper.WallpaperService+import android.view.Choreographer+import android.view.SurfaceHolder+import androidx.core.net.toUri+import androidx.media3.common.C+import androidx.media3.common.MediaItem+import androidx.media3.common.Player+import androidx.media3.common.util.UnstableApi+import androidx.media3.exoplayer.ExoPlayer+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlin.math.max++/**+ * Live wallpaper that renders either a muted, looping video (via ExoPlayer) or an+ * animated GIF (via [AnimatedImageDrawable] drawn to the engine surface), always+ * center-cropped to fill the screen. The media URI and its type are chosen in the+ * photos viewer and persisted through [DataStoreUtils]; the engine reads them when+ * its surface is created.+ *+ * Runs in the app's own process, so it inherits the app's READ_MEDIA_* access and+ * can read the MediaStore content URI directly — no persistable URI grant needed.+ */+@UnstableApi+class LiveWallpaperService : WallpaperService() {++ override fun onCreateEngine(): Engine = LiveWallpaperEngine()++ private inner class LiveWallpaperEngine : Engine() {+ // Engine callbacks run on the main thread; keep our coroutines there too so+ // ExoPlayer and the Choreographer draw loop stay on the thread they require.+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)++ private var exoPlayer: ExoPlayer? = null++ private var gifDrawable: AnimatedImageDrawable? = null+ private var surfaceWidth = 0+ private var surfaceHeight = 0+ private var choreographerCallback: Choreographer.FrameCallback? = null+ private var drawing = false++ private var uri: Uri? = null+ private var isVideo = false++ // AnimatedImageDrawable needs a callback attached to run; we drive redraws+ // ourselves via Choreographer, so these are intentionally no-ops.+ private val drawableCallback = object : Drawable.Callback {+ override fun invalidateDrawable(who: Drawable) {}+ override fun scheduleDrawable(who: Drawable, what: Runnable, `when`: Long) {}+ override fun unscheduleDrawable(who: Drawable, what: Runnable) {}+ }++ override fun onSurfaceCreated(holder: SurfaceHolder) {+ super.onSurfaceCreated(holder)+ scope.launch {+ val ds = DataStoreUtils.getInstance(applicationContext)+ val uriStr = ds.getStringAwait(KEY_WALLPAPER_URI) ?: return@launch+ isVideo = ds.getBooleanAwait(KEY_WALLPAPER_IS_VIDEO)+ uri = uriStr.toUri()+ if (isVideo) startVideo(holder) else startGif()+ }+ }++ override fun onSurfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {+ super.onSurfaceChanged(holder, format, width, height)+ surfaceWidth = width+ surfaceHeight = height+ gifDrawable?.let { updateGifBounds(it) }+ }++ override fun onVisibilityChanged(visible: Boolean) {+ super.onVisibilityChanged(visible)+ if (isVideo) {+ exoPlayer?.playWhenReady = visible+ } else {+ if (visible) startDrawLoop() else stopDrawLoop()+ }+ }++ override fun onSurfaceDestroyed(holder: SurfaceHolder) {+ super.onSurfaceDestroyed(holder)+ releaseVideo()+ stopDrawLoop()+ gifDrawable = null+ }++ override fun onDestroy() {+ super.onDestroy()+ scope.cancel()+ releaseVideo()+ stopDrawLoop()+ gifDrawable = null+ }++ // --- Video ------------------------------------------------------------++ private fun startVideo(holder: SurfaceHolder) {+ val u = uri ?: return+ exoPlayer = ExoPlayer.Builder(applicationContext).build().apply {+ setMediaItem(MediaItem.fromUri(u))+ repeatMode = Player.REPEAT_MODE_ONE+ volume = 0f+ setVideoScalingMode(C.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING)+ setVideoSurface(holder.surface)+ prepare()+ playWhenReady = isVisible+ }+ }++ private fun releaseVideo() {+ exoPlayer?.release()+ exoPlayer = null+ }++ // --- GIF --------------------------------------------------------------++ private fun startGif() {+ val u = uri ?: return+ scope.launch {+ val d = withContext(Dispatchers.IO) {+ runCatching {+ ImageDecoder.decodeDrawable(+ ImageDecoder.createSource(contentResolver, u)+ ) as? AnimatedImageDrawable+ }.getOrNull()+ } ?: return@launch+ d.repeatCount = AnimatedImageDrawable.REPEAT_INFINITE+ d.callback = drawableCallback+ gifDrawable = d+ updateGifBounds(d)+ if (isVisible) startDrawLoop()+ }+ }++ /** Center-crop the drawable to fill the surface (scale = max(sw/iw, sh/ih)). */+ private fun updateGifBounds(d: AnimatedImageDrawable) {+ val iw = d.intrinsicWidth+ val ih = d.intrinsicHeight+ if (iw <= 0 || ih <= 0 || surfaceWidth <= 0 || surfaceHeight <= 0) return+ val scale = max(surfaceWidth.toFloat() / iw, surfaceHeight.toFloat() / ih)+ val dw = (iw * scale).toInt()+ val dh = (ih * scale).toInt()+ val left = (surfaceWidth - dw) / 2+ val top = (surfaceHeight - dh) / 2+ d.setBounds(left, top, left + dw, top + dh)+ }++ private fun startDrawLoop() {+ val d = gifDrawable ?: return+ if (drawing) return+ drawing = true+ if (!d.isRunning) d.start()+ val cb = choreographerCallback ?: object : Choreographer.FrameCallback {+ override fun doFrame(frameTimeNanos: Long) {+ if (!drawing) return+ drawGifFrame()+ Choreographer.getInstance().postFrameCallback(this)+ }+ }.also { choreographerCallback = it }+ Choreographer.getInstance().postFrameCallback(cb)+ }++ private fun stopDrawLoop() {+ drawing = false+ choreographerCallback?.let { Choreographer.getInstance().removeFrameCallback(it) }+ gifDrawable?.takeIf { it.isRunning }?.stop()+ }++ private fun drawGifFrame() {+ val d = gifDrawable ?: return+ val canvas = surfaceHolder.lockCanvas() ?: return+ try {+ canvas.drawColor(Color.BLACK)+ d.draw(canvas)+ } finally {+ surfaceHolder.unlockCanvasAndPost(canvas)+ }+ }+ }++ companion object {+ const val KEY_WALLPAPER_URI = "wallpaper_uri"+ const val KEY_WALLPAPER_IS_VIDEO = "wallpaper_is_video"+ }+}
photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.ktindex ec28985a89..52909e5ff1 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt@@ -55,6 +55,7 @@ import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow@@ -92,6 +93,7 @@ import com.vayunmathur.photos.R import com.vayunmathur.photos.Route import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.util.GalleryViewModel+import com.vayunmathur.photos.util.LiveWallpaperLauncher import com.vayunmathur.photos.util.PhotoMapViewModel import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver@@ -101,6 +103,7 @@ import kotlin.time.Instant import kotlinx.coroutines.delay import kotlinx.coroutines.flow.filter import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.distinctUntilChanged@@ -113,6 +116,7 @@ fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapVie val photosAll by galleryViewModel.photos.collectAsState() val photos = overridePhotosList ?: photosAll.filter { !it.isTrashed } val context = LocalContext.current+ val coroutineScope = rememberCoroutineScope() // Photos deleted from within this viewer, hidden immediately so the pager // advances to the next photo without waiting for the MediaStore resync. val locallyDeleted = remember { mutableStateListOf<Long>() }@@ -236,7 +240,13 @@ fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapVie context.startActivity(intent) }, onSetWallpaper = { p ->- backStack?.add(Route.Wallpaper(p.id, p.uri))+ if (p.videoData != null || p.isGif) {+ coroutineScope.launch {+ LiveWallpaperLauncher.apply(context, p.uri, p.videoData != null)+ }+ } else {+ backStack?.add(Route.Wallpaper(p.id, p.uri))+ } }, onDelete = onDeletePhoto )@@ -525,10 +535,10 @@ fun PhotoDetailView( modifier = Modifier.align(Alignment.End), verticalAlignment = Alignment.CenterVertically ) {+ IconButton(onClick = { onSetWallpaper(photo) }) {+ IconWallpaper(tint = Color.White)+ } if (photo.videoData == null) {- IconButton(onClick = { onSetWallpaper(photo) }) {- IconWallpaper(tint = Color.White)- } IconButton(onClick = onEditPhoto) { IconEdit(tint = Color.White) } } IconButton(@@ -685,11 +695,13 @@ fun VideoPlayer( } // Seek bar overlay, shares the metadata-visible gate with the play/pause button.+ // Anchored to the top so it never sits under the centered play/pause control or+ // the bottom metadata/button card, both of which are drawn over the video. AnimatedVisibility( visible = isMetadataVisible && durationMs > 0, enter = fadeIn(), exit = fadeOut(),- modifier = Modifier.align(Alignment.BottomCenter)+ modifier = Modifier.align(Alignment.TopCenter) ) { val sliderValue = (if (isScrubbing) scrubPos else positionMs.toFloat())
photos/src/main/java/com/vayunmathur/photos/util/LiveWallpaperLauncher.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/LiveWallpaperLauncher.kt b/photos/src/main/java/com/vayunmathur/photos/util/LiveWallpaperLauncher.ktnew file mode 100644index 0000000000..4a2889190f--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/util/LiveWallpaperLauncher.kt@@ -0,0 +1,52 @@+package com.vayunmathur.photos.util++import android.app.WallpaperManager+import android.content.ActivityNotFoundException+import android.content.ComponentName+import android.content.Context+import android.content.Intent+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.photos.R+import com.vayunmathur.photos.service.LiveWallpaperService++/**+ * Persists the chosen media as the live wallpaper source and hands off to the system+ * live-wallpaper preview, where the user taps the final "Set wallpaper" button.+ * Android does not allow a third-party app to silently apply an animated wallpaper.+ */+object LiveWallpaperLauncher {++ suspend fun apply(context: Context, uri: String, isVideo: Boolean) {+ val ds = DataStoreUtils.getInstance(context.applicationContext)+ ds.setString(LiveWallpaperService.KEY_WALLPAPER_URI, uri)+ ds.setBoolean(LiveWallpaperService.KEY_WALLPAPER_IS_VIDEO, isVideo)++ val component = ComponentName(context, LiveWallpaperService::class.java)+ val direct = Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER).apply {+ putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, component)+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ // Attempt to launch directly rather than pre-checking with resolveActivity:+ // package-visibility rules make resolveActivity return null for the system+ // wallpaper picker even when it exists, so a pre-check falsely reports failure.+ try {+ context.startActivity(direct)+ return+ } catch (_: ActivityNotFoundException) {+ }++ // Some devices don't honour the direct component intent; fall back to the+ // generic live-wallpaper chooser.+ val chooser = Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER).apply {+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ try {+ context.startActivity(chooser)+ return+ } catch (_: ActivityNotFoundException) {+ }++ AppMessages.show(context.getString(R.string.live_wallpaper_unavailable))+ }+}
photos/src/main/res/values/strings.xml
diff --git a/photos/src/main/res/values/strings.xml b/photos/src/main/res/values/strings.xmlindex bf3abe9c09..e193735f40 100644--- a/photos/src/main/res/values/strings.xml+++ b/photos/src/main/res/values/strings.xml@@ -491,4 +491,6 @@ <!-- Desc: drag to draw a line --> <string name="editor_desc_shape_line">Drag to draw a line.</string> <string name="edit_with_label">Edit with My App</string>+ <string name="live_wallpaper_description">Animated wallpaper from your photos</string>+ <string name="live_wallpaper_unavailable">Live wallpapers are not supported on this device</string> </resources>
photos/src/main/res/xml/live_wallpaper.xml
diff --git a/photos/src/main/res/xml/live_wallpaper.xml b/photos/src/main/res/xml/live_wallpaper.xmlnew file mode 100644index 0000000000..707f77eac6--- /dev/null+++ b/photos/src/main/res/xml/live_wallpaper.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<wallpaper xmlns:android="http://schemas.android.com/apk/res/android"+ android:thumbnail="@mipmap/ic_launcher"+ android:description="@string/live_wallpaper_description" />