Android Studio 进度栏未正确更新

问题描述 投票:0回答:1

目前正在制作一个音乐播放器,其中有一个进度条,可以跟踪音乐播放的当前进度。然而,我已经厌倦了许多不同的方法,并且不确定是否是因为我完成线程的方式,或者是否是其他可能非常明显但我没有看到它的东西,进度条似乎不想跟踪/设置进度除非我暂停媒体文件并继续播放。 (例如,我启动一个 mp3 文件,音乐开始播放,但进度条没有更新。我暂停音乐并再次按继续/播放,然后进度条会跳转到音乐的实际当前进度并实际上不断更新)

当前正在使用服务来播放音乐并调用服务音乐播放器。

    public static BackgroundPlayer bp = new BackgroundPlayer();
    public static MP3Player player = bp.getPlayer();
    ProgressBar musicProgress;
    private String musicURL;
    private boolean isRunning;
    private float playbackspeed;

    private int progress;
    private int duration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_current_music);

        if(savedInstanceState != null)
        {
            progress = savedInstanceState.getInt("Progress");
            duration = savedInstanceState.getInt("Duration");
            isRunning = savedInstanceState.getBoolean("Running");
            playbackspeed = savedInstanceState.getFloat("SPEED");


            duration = player.getDuration();
            musicProgress.setMax(duration);

            if(isRunning)
            {
                new Thread( () -> {
                    while(isRunning)
                    {
                        progress = player.getProgress();
                        musicProgress.setProgress(progress);
                    }
                }).start();
            }

        }
    }


    public void onPlayClick (View v)
    {
        Intent intent = new Intent(CurrentMusic.this, BackgroundPlayer.class);
                player.stop();
                stopService(intent);
                startService(intent);
        duration = player.getDuration();
        musicProgress.setMax(duration);
        new Thread( () -> {
            while(isRunning)
            {
                progress = player.getProgress();
                musicProgress.setProgress(progress);
            }
        }).start();
    }

我的后台播放器是我的服务

android android-service android-progressbar android-thread
1个回答
0
投票

问题是你尝试从非 UI 线程更新

musicPlayer
(这是 UI 组件)。只有主(UI)线程可以更新UI。

尝试用

runOnUiThread()
包装更新逻辑:

new Thread( () -> {
    while(isRunning) {
        progress = player.getProgress();
        runOnUiThread(() -> musicProgress.setProgress(progress));
    }
}).start();

更多详细信息和更新 UI 的其他选项位于:https://developer.android.com/guide/components/processes-and-threads#WorkerThreads

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.