Home > Software engineering >  How to set wallpaper in android studio from url(kotlin)
How to set wallpaper in android studio from url(kotlin)

Time:10-06

I am a novice developer. Can someone help me how can I set the image I have the url as the wallpaper title when I click a button? (Kotlin)

CodePudding user response:

You could go through this official documentation for android developers. Load and display images from the Internet

CodePudding user response:

You need to use WallpaperManager to set the wallpaper, and there's a handy setStream function that takes an InputStream. So instead of having to download the image, you can just open a stream to it, and pass that to WallpaperManager:

button.setOnClickListener {
    lifecycleScope.launch(Dispatchers.IO) {
        val inputStream = URL("https://cdn2.thecatapi.com/images/oe.jpg").openStream()
        WallpaperManager.getInstance(requireContext()).setStream(inputStream)
    }
}

Or if you don't want to use coroutines (you should, it's safer since they get cancelled automatically) you could run it in a worker thread

thread(start = true) {
    val inputStream = URL("https://cdn2.thecatapi.com/images/oe.jpg").openStream()
    WallpaperManager.getInstance(requireContext()).setStream(inputStream)    
}

But you need to do one of those things, because you can't do network stuff on the main thread.

You also need the SET_WALLPAPER and INTERNET permissions in your AndroidManifest.xml:

// inside the main <manifest> block
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.INTERNET" />
  • Related