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

时间:2018-04-12 10:26:23

标签: 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){

        }
    }



}

如何修复错误?谢谢。

1 个答案:

答案 0 :(得分:1)

您无法从后台线程执行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;
        }
    });
...
}