DEV Community

Kodnex Technologies
Kodnex Technologies

Posted on Originally published at nexwall.kodnextech.com

How to Set a Wallpaper Programmatically in Android with Kotlin (Retrofit + WallpaperManager)

Fetch high-resolution portrait wallpapers from a REST API and apply them to the home or lock screen. This covers the memory-safe approach, the right flags, and a daily auto-changer with WorkManager.

Disclosure: I build NexWall, the wallpaper API used as the data source here. The WallpaperManager parts apply to any image URL, so the techniques work just as well with other sources.

Setting a wallpaper from code looks like a one-liner: WallpaperManager.setBitmap(bitmap). In practice there are a few traps:

  • Decoding a 4K image into a Bitmap can crash low-end devices with an out-of-memory error.
  • Home screen vs lock screen needs flags that only exist on API 24+.
  • Doing it on the main thread causes jank or ANRs.
  • Some devices (enterprise or kids' profiles) don't allow wallpaper changes at all.

This guide walks through a clean implementation:

  1. Fetch wallpapers from a wallpaper REST API with Retrofit
  2. Download the chosen image with OkHttp
  3. Stream it into WallpaperManager with the right flags
  4. Optionally, schedule a daily auto wallpaper change with WorkManager

The data source

I'll use the NexWall wallpaper API. It returns curated 9:16 wallpapers in portrait HD up to 4K (most around 1440x2560) across 49 categories. The free tier is 100 requests/day and 60/minute with no credit card, covers the non-premium static categories, and allows commercial use (ads, subscriptions, in-app purchases, paid apps) under the Developer API License. Get a key at https://nexwall.kodnextech.com/developers/register, or try it first with no key at all:

curl "https://nexwall.kodnextech.com/api/developer/v1/demo/wallpapers?sort=random&per_page=5"
Enter fullscreen mode Exit fullscreen mode

The keyless demo returns up to 10 wallpapers per request (10 requests/minute, 30/day per IP).

  • Base URL: https://nexwall.kodnextech.com/api/developer/v1
  • Auth: Authorization: Bearer YOUR_API_KEY
  • Feed: GET /wallpapers?page=&per_page=&category_id=&sort=&search=

1. Dependencies

app/build.gradle.kts:

dependencies {
    implementation("com.squareup.retrofit2:retrofit:2.11.0")
    implementation("com.squareup.retrofit2:converter-gson:2.11.0")
    implementation("com.squareup.okhttp3:okhttp:4.12.0")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
    implementation("androidx.work:work-runtime-ktx:2.9.1")
}
Enter fullscreen mode Exit fullscreen mode

(Use whatever current versions your project already uses. Nothing here depends on a specific release.)

AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
Enter fullscreen mode Exit fullscreen mode

SET_WALLPAPER is a normal permission, so it's granted at install time and you don't need a runtime prompt.

2. Keep the key out of source control

For a prototype, put the key in local.properties (which is git-ignored by default) and expose it through BuildConfig:

// app/build.gradle.kts
import java.util.Properties

val localProps = Properties().apply {
    val f = rootProject.file("local.properties")
    if (f.exists()) f.inputStream().use { load(it) }
}

android {
    buildFeatures { buildConfig = true }
    defaultConfig {
        buildConfigField(
            "String", "NEXWALL_API_KEY",
            "\"${localProps.getProperty("NEXWALL_API_KEY", "")}\""
        )
    }
}
Enter fullscreen mode Exit fullscreen mode
# local.properties
NEXWALL_API_KEY=YOUR_API_KEY
Enter fullscreen mode Exit fullscreen mode

For production, anything in BuildConfig can be extracted from the APK. Route requests through your own backend proxy that holds the key (and caches responses), then point Retrofit's baseUrl at the proxy. This is also how you keep many users within one daily quota.

3. Models and the Retrofit service

The feed response looks like this (trimmed):

{
  "data": [
    {
      "id": 1042,
      "category_id": 1,
      "image_url": "https://nexwall.kodnextech.com/storage/wallpapers/example.webp",
      "thumbnail_url": "https://nexwall.kodnextech.com/storage/thumbnails/example.webp",
      "type": "image",
      "tags": "amoled, dark, minimal",
      "resolution": "1440x2560"
    }
  ],
  "current_page": 1,
  "last_page": 1,
  "per_page": 50,
  "total": 1,
  "plan": "free",
  "remaining_requests_today": 99
}
Enter fullscreen mode Exit fullscreen mode
import com.google.gson.annotations.SerializedName

data class WallpaperListResponse(
    val data: List<WallpaperDto>,
    @SerializedName("current_page") val currentPage: Int,
    @SerializedName("last_page") val lastPage: Int,
    @SerializedName("remaining_requests_today") val remainingRequestsToday: Int?
)

data class WallpaperDto(
    val id: Long,
    @SerializedName("category_id") val categoryId: Long?,
    @SerializedName("image_url") val imageUrl: String,
    @SerializedName("thumbnail_url") val thumbnailUrl: String?,
    val type: String,
    val tags: String?,
    val resolution: String?
)
Enter fullscreen mode Exit fullscreen mode
import retrofit2.http.GET
import retrofit2.http.Query

interface NexWallService {
    @GET("wallpapers")
    suspend fun wallpapers(
        @Query("page") page: Int = 1,
        @Query("per_page") perPage: Int = 30,
        @Query("sort") sort: String = "newest",   // newest | oldest | popular | random
        @Query("category_id") categoryId: Int? = null,
        @Query("search") search: String? = null,  // 2..100 chars, matches tags
        @Query("type") type: String = "image"
    ): WallpaperListResponse
}
Enter fullscreen mode Exit fullscreen mode

Retrofit drops @Query parameters whose value is null, so optional filters only appear in the URL when you set them.

Instead of adding @Header("Authorization") to every method, use an interceptor:

import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object NexWallClient {
    private const val BASE_URL = "https://nexwall.kodnextech.com/api/developer/v1/"

    val http: OkHttpClient = OkHttpClient.Builder()
        .addInterceptor { chain ->
            val req = chain.request().newBuilder()
                .header("Authorization", "Bearer ${BuildConfig.NEXWALL_API_KEY}")
                .header("Accept", "application/json")
                .build()
            chain.proceed(req)
        }
        .connectTimeout(15, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build()

    val service: NexWallService = Retrofit.Builder()
        .baseUrl(BASE_URL)            // must end with "/"
        .client(http)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(NexWallService::class.java)
}
Enter fullscreen mode Exit fullscreen mode

One subtlety: this http client adds the API key to every request, including image downloads. Image URLs are plain public file URLs, so use a separate client without the interceptor for downloads (shown below). Your key shouldn't travel anywhere it isn't needed.

Handling errors

The API returns 401 for a bad key, 422 for invalid parameters, and 429 when you hit the per-minute or daily limit (with a Retry-After header). With suspend functions, Retrofit throws HttpException on non-2xx responses:

import retrofit2.HttpException

suspend fun loadFeed(): Result<WallpaperListResponse> = try {
    Result.success(NexWallClient.service.wallpapers(sort = "popular"))
} catch (e: HttpException) {
    val msg = when (e.code()) {
        401 -> "Invalid API key"
        429 -> "Rate limited, retry after ${e.response()?.headers()?.get("Retry-After")}s"
        422 -> "Bad query parameters"
        else -> "HTTP ${e.code()}"
    }
    Result.failure(IllegalStateException(msg, e))
} catch (e: java.io.IOException) {
    Result.failure(e) // network problem
}
Enter fullscreen mode Exit fullscreen mode

4. Setting the wallpaper (the memory-safe way)

The key idea is to stream the image into WallpaperManager rather than decoding it into a Bitmap yourself. A 2160x3840 image is roughly 33 MB as an ARGB_8888 bitmap. setStream() lets the system decode it efficiently. One caveat: the setStream reference docs say the stream should be a JPEG or PNG image. If your source serves WebP, decode it yourself with BitmapFactory (use inSampleSize to stay near the screen size) and pass the result to setBitmap instead.

import android.app.WallpaperManager
import android.content.Context
import android.os.Build
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException

enum class WallpaperTarget { HOME, LOCK, BOTH }

object WallpaperSetter {
    // Plain client: no API key on image downloads.
    private val downloadClient = OkHttpClient()

    suspend fun setFromUrl(
        context: Context,
        imageUrl: String,
        target: WallpaperTarget = WallpaperTarget.BOTH
    ) = withContext(Dispatchers.IO) {
        val wm = WallpaperManager.getInstance(context.applicationContext)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !wm.isWallpaperSupported) throw IllegalStateException("Wallpapers not supported on this device")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !wm.isSetWallpaperAllowed) {
            throw IllegalStateException("Wallpaper changes are blocked by device policy")
        }

        val request = Request.Builder().url(imageUrl).build()
        downloadClient.newCall(request).execute().use { response ->
            if (!response.isSuccessful) throw IOException("Download failed: HTTP ${response.code}")
            val stream = response.body?.byteStream() ?: throw IOException("Empty body")

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                val flags = when (target) {
                    WallpaperTarget.HOME -> WallpaperManager.FLAG_SYSTEM
                    WallpaperTarget.LOCK -> WallpaperManager.FLAG_LOCK
                    WallpaperTarget.BOTH -> WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK
                }
                // visibleCropHint = null: let the system centre-crop; allowBackup = true
                wm.setStream(stream, null, true, flags)
            } else {
                // Pre-Nougat has no separate lock screen wallpaper API.
                wm.setStream(stream)
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Calling it from a ViewModel:

class WallpaperViewModel(app: Application) : AndroidViewModel(app) {
    val status = MutableStateFlow<String?>(null)

    fun apply(wallpaper: WallpaperDto, target: WallpaperTarget) {
        viewModelScope.launch {
            status.value = "Applying…"
            status.value = runCatching {
                WallpaperSetter.setFromUrl(getApplication(), wallpaper.imageUrl, target)
            }.fold(
                onSuccess = { "Wallpaper set" },
                onFailure = { "Failed: ${it.message}" }
            )
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Why not setBitmap?

setBitmap is fine if you already have a bitmap, for example because you applied a filter or a custom crop. For the plain "download and apply" flow, setStream avoids a full in-memory decode on your side.

Letting the user crop

If you'd rather show the system's crop UI, save the image to a file, expose it through a FileProvider, and launch wm.getCropAndSetWallpaperIntent(contentUri). Note that the system crop activity isn't available on every device or launcher, so wrap it in a try/catch and fall back to setStream.

5. Bonus: a daily auto wallpaper changer with WorkManager

This is quota-friendly: one API request per day. sort=random&per_page=1 returns a single random wallpaper.

import android.content.Context
import androidx.work.*
import java.util.concurrent.TimeUnit

class DailyWallpaperWorker(ctx: Context, params: WorkerParameters) :
    CoroutineWorker(ctx, params) {

    override suspend fun doWork(): Result = try {
        val categoryId = inputData.getInt("category_id", -1).takeIf { it > 0 }
        val feed = NexWallClient.service.wallpapers(
            perPage = 1, sort = "random", categoryId = categoryId
        )
        val wp = feed.data.firstOrNull() ?: return Result.retry()
        WallpaperSetter.setFromUrl(applicationContext, wp.imageUrl, WallpaperTarget.HOME)
        Result.success()
    } catch (e: retrofit2.HttpException) {
        if (e.code() == 429) Result.retry() else Result.failure()
    } catch (e: java.io.IOException) {
        Result.retry()
    }

    companion object {
        fun schedule(context: Context, categoryId: Int? = null) {
            val request = PeriodicWorkRequestBuilder<DailyWallpaperWorker>(24, TimeUnit.HOURS)
                .setConstraints(
                    Constraints.Builder()
                        .setRequiredNetworkType(NetworkType.UNMETERED) // be kind to mobile data
                        .build()
                )
                .setInputData(workDataOf("category_id" to (categoryId ?: -1)))
                .build()

            WorkManager.getInstance(context).enqueueUniquePeriodicWork(
                "daily_wallpaper",
                ExistingPeriodicWorkPolicy.UPDATE,
                request
            )
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Call DailyWallpaperWorker.schedule(context, categoryId = 1) from a settings toggle. WorkManager handles Doze, reboots, and retries with backoff.

Checklist before shipping

  • [ ] API key is not in the APK (use a backend proxy in production)
  • [ ] Wallpaper is set from Dispatchers.IO, never the main thread
  • [ ] isSetWallpaperAllowed is checked (managed devices)
  • [ ] Grids use thumbnail_url; only the apply action downloads image_url
  • [ ] 429 handled with Retry-After / backoff
  • [ ] Licensing checked: on NexWall, monetized Play Store apps (ads, subscriptions, in-app purchases) are allowed on every plan, including Free (license)

A complete, runnable Jetpack Compose app using this exact pattern is on GitHub: nexwall-android-kotlin-wallpaper-app (MIT).

Wrapping up

The pattern is: Retrofit for the feed, a plain OkHttp client for the bytes, setStream with flags, and WorkManager for anything scheduled. It works the same whether the images come from NexWall or another source.

If you want to try NexWall's free wallpaper API: docs are at https://nexwall.kodnextech.com/wallpaper-api/docs, the OpenAPI spec is at https://nexwall.kodnextech.com/openapi.json, you can get a free key (100 requests/day) at https://nexwall.kodnextech.com/developers/register, and the keyless demo at https://nexwall.kodnextech.com/api/developer/v1/demo/wallpapers needs no signup.

Disclosure, again: I work on NexWall. Questions, corrections, and feature requests are very welcome in the responses.

Top comments (0)