当我按下一首歌曲按钮几次播放歌曲后,应用程序崩溃并且 logcat 在 Update_SeekBar 线程中显示错误

After playing a song when i press next song button a few times, app crashes and logcat is showing the error in Update_SeekBar thread

我想制作一个音乐播放器。一切正常,但当我按下下一首或上一首歌曲按钮几次(5 到 6 次)时,应用程序崩溃了。 Logcat 给出了行中的错误:currentPosition = mediaPlayer.currentPosition

updateSeekBar = Thread(Runnable {
            var totalDuration = mediaPlayer.duration
            var currentPosition =  0

            while (currentPosition < totalDuration) {
                try {
                    sleep(500)
                    currentPosition = mediaPlayer.currentPosition
                    songSeekBar.setProgress(currentPosition)
                }
                catch (e : InterruptedException){
                    e.printStackTrace()
                }
            }
        })

Logcat Error msg: 2019-07-06 08:30:01.779 9951-10013/com.example.musicplayer E/AndroidRuntime: FATAL EXCEPTION: Thread-7 Process: com.example.musicplayer, PID: 9951 java.lang.IllegalStateException at android.media.MediaPlayer.getCurrentPosition(Native Method) at com.example.musicplayer.PlayMusicActivity$onCreate.run(PlayMusicActivity.kt:68) at java.lang.Thread.run(Thread.java:764)

Note: Line # 68 = currentPosition = mediaPlayer.currentPosition

您正在从非 UI 线程访问搜索栏的 UI。所以试试下面的代码。

    updateSeekBar = Thread(Runnable {
        var totalDuration = mediaPlayer.duration
        var currentPosition =  0

        while (currentPosition < totalDuration) {
            try {
//                  Add UI thread here
                runOnUiThread(Runnable {
                    currentPosition = mediaPlayer.currentPosition
                    songSeekBar.setProgress(currentPosition)
                });
                sleep(500)
            }
            catch (e : InterruptedException){
                e.printStackTrace()
            }
        }
    })