Android Studio 方法 getCurrentPosition 必须从 UI 线程调用,当前推断线程是 worker

标签 android android-asynctask

我使用 VideoProgress 从异步任务开发视频并收到此错误 方法 getCurrentPosition 必须从 UI 线程调用,当前推断线程是 worker。

public class VideoProgress extends AsyncTask<Void, Integer, Void>{
    @Override
    protected Void doInBackground(Void... voids){


        do{
            if(isPlaying) {
                current = vv.getCurrentPosition() / 1000;
                publishProgress(current);
            }
        }while (currentProgress.getProgress() <= 100);

        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values){
        super.onProgressUpdate(values);

        try {
            int currentPercent = values[0] * 100/duration;
            currentProgress.setProgress(currentPercent);
            String currentString = String.format("%02d:%02d", values[0] / 60, values[0] % 60);
            curTime.setText(currentString);
        }catch (Exception e){

        }
    }



}

如何修复错误?谢谢。

最佳答案

您不能从后台线程执行 UI 组件。您需要使用 runOnUIThread 或 Handler。

您可以执行以下操作:

if(isPlaying) {

    runOnUiThread(new Runnable() {
            @Override
            public void run() {
                 current = vv.getCurrentPosition() / 1000;   
            }
        });
...
}

if(isPlaying) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            current = vv.getCurrentPosition() / 1000;
        }
    });
...
}

关于Android Studio 方法 getCurrentPosition 必须从 UI 线程调用,当前推断线程是 worker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49794163/

相关文章:

android - Esri ArcGIS 范围完成渲染/下载切片通知

jquery - 连接到 192.168.x.x 时如何使用 navigator.geolocation 获取经纬度信息

android - 在 AsyncTask 中收到每个项目后调用 notifyDataSetChanged

android - 如何防止双击刷新按钮

android - 为什么Android HCE 不支持Mifare Classic 类型?

android - AudioPolicyManagerBase 错误

android - 我们可以放大缩小我们在 Canvas 上绘制的绘图 android

安卓异步任务 : what is difference between execute() and get()?

android - `doInBackground()` 不接受类型为 void 的 `AsyncTask`?

android - AsyncTask 没有传递进度(super.onprogressupdate 做什么?)