0

I am building a current weather app using the openweathermap API in Kotlin and would like the background to change depending on the state of the weather, e.g. in winter when it snows, the background is snowy (from my drawable folder) and so on.

Below is a function that should change the background depending on the id. But I need to make it automatic.

private fun updateUI(id: Int){

    if(id in 200..232){

        binding.ivWeatherBg.setImageResource(R.drawable.thunderstorm_bg)

        binding.ivWeatherIcon.setImageResource(R.drawable.thunderstorm)

    } else if (id in 300..321){

        binding.ivWeatherBg.setImageResource(R.drawable.drizzle_bg)

        binding.ivWeatherIcon.setImageResource(R.drawable.drizzle)

    } else if (id in 500..531){

        binding.ivWeatherBg.setImageResource(R.drawable.drizzle_bg)

        binding.ivWeatherIcon.setImageResource(R.drawable.rain)

    } else if (id in 600..620){

        binding.ivWeatherBg.setImageResource(R.drawable.snow_bg)

        binding.ivWeatherIcon.setImageResource(R.drawable.snow)

    } else if (id in 701..781){

        binding.ivWeatherBg.setImageResource(R.drawable.mist_bg)

        binding.ivWeatherIcon.setImageResource(R.drawable.mist)

    } else if (id == 800){

        binding.ivWeatherBg.setImageResource(R.drawable.clear_bg)

        binding.ivWeatherIcon.setImageResource(R.drawable.clear)

    } else {

        binding.ivWeatherBg.setImageResource(R.drawable.clouds_bg)

        binding.ivWeatherIcon.setImageResource(R.drawable.clouds)

    }

}

I seem to have prepared everything, but when I add the background change function, it all depends on the weather id that I need to write, and I want to automate all this according to the weather.

KuS-
  • 1
  • 1
  • 3
  • Do you have updateUI() being called once an hour or something in the background to do this and its not working - or is that what you want to set up? – ryankuck Aug 27 '23 at 21:37
  • @ryankuck I want to set up the picture on the background to be changed every time when weather condition is changed. I just don't know how call it. – KuS- Aug 28 '23 at 14:15
  • Please see [ask], then revise your post title to ask a clear, specific question _about your code_, not your app requirements. – isherwood Aug 28 '23 at 14:41
  • Hi, did I answer your question? If so please up vote the answer or clarify the question. Thanks! – ryankuck Aug 30 '23 at 03:17

1 Answers1

0

I would recommend defining a long running background service that runs on an interval. Similar to this question.

Using the alarm manager you can trigger the service code to run on an interval.

The in the code that runs every interval you can make the api call to get the current weather and update the background photo accordingly.

ryankuck
  • 320
  • 3
  • 15