我使用 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/