'Android "visibility" doesn't change if next instruction take long time
I have following situation in my fragment.
@SuppressLint("ClickableViewAccessibility")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.streaming_fragment, container, false)
val button = view.findViewById<Button>(R.id.radio_button)
val pb = view.findViewById<ProgressBar>(R.id.progressBar)
button.setOnClickListener {
if (mediaPlayer.isPlaying) {
this.mediaPlayer.pause();
} else {
pb.visibility = View.VISIBLE
this.mediaPlayer.reset()
this.mediaPlayer.setDataSource(
requireContext(),
Uri.parse("https://xxx.mp3")
)
this.mediaPlayer.prepare()
this.mediaPlayer.start();
pb.visibility = View.INVISIBLE
}
this.renderButtonBackground()
}
return view;
}
But the instruction pb.visibility = View.VISIBLE seems not working, beacause the thread of view refresh is "locked" by following instruction
this.mediaPlayer.reset()
this.mediaPlayer.setDataSource(
requireContext(),
Uri.parse("https://xxx.mp3")
)
this.mediaPlayer.prepare()
this.mediaPlayer.start();
In fact, if I comment this line
pb.visibility = View.INVISIBLE
the spinner appear after the MediaPlayer started playing streaming audio.
How can I avoid this behavoir? Is there a way to give priority to first instruction?
Thanks... Sorry but I am new on Android.
Solution 1:[1]
All the code you have shown is running on the main (UI) thread. The documentation clearly states that MediaPlayer.prepare() can take a long time and should never be called on the main (UI) thread. The documentation even explains how to do this using MediaPlayer.prepareAsync().
See https://developer.android.com/guide/topics/media/mediaplayer?hl=en#preparingasync
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David Wasser |
