0

How can I get an image in Kotlin via URL as a background image title when I click on a button?

Benjamin Buch
  • 4,752
  • 7
  • 28
  • 51

2 Answers2

1

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

hayzie101
  • 23
  • 5
1

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" />
cactustictacs
  • 17,935
  • 2
  • 14
  • 25