等待 UI 线程在 Android 中完成操作
Waiting for UI Thread to finish operation in Android
我在 onCreate()
方法中遇到这种情况:
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
new Thread(() -> {
Object obj;
while (true) {
// update obj
runOnUiThread(() -> {
// display obj
});
}
}).start();
}
这里的问题是更新操作与显示操作不同步:我总是跳过一个值,因为 obj
在 UI 线程能够显示其旧值之前更新值。
等待 UI 线程完成显示 obj
的工作然后才继续下一次迭代的正确方法是什么?
您可以在此处使用 回调
喜欢,
//Extending the Activity is left here since it isn't the subject
public class MyClass implements MyThread.CallbackListener{
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
new MyThread(this).start();
//Your codes that do not require synchronization with the above thread
}
@Override
public void onObjectUpdated(Object obj){
//Your code that needs to be synchronized. In your case display your object here
}
}
而您的 MyThread class 将是
public class MyThread extends Thread{
Object obj;
CallbackListener listener;
public MyThread(CallbackListener listener){
this.listener = listener;
}
public void run(){
while (true) {
// update obj
listener.onObjectUpdated(obj);
}
}
public interface CallbackListener{
void onObjectUpdated(Object obj);
}
}
我们在这里所做的只是在对象更新后进行方法调用。
当对象更新后,您在 MyClass 中的 onObjectUpdated 方法将被调用,以使您的代码同步。您可以将任何非同步代码放入 onCreate 方法本身。
我在 onCreate()
方法中遇到这种情况:
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
new Thread(() -> {
Object obj;
while (true) {
// update obj
runOnUiThread(() -> {
// display obj
});
}
}).start();
}
这里的问题是更新操作与显示操作不同步:我总是跳过一个值,因为 obj
在 UI 线程能够显示其旧值之前更新值。
等待 UI 线程完成显示 obj
的工作然后才继续下一次迭代的正确方法是什么?
您可以在此处使用 回调
喜欢,
//Extending the Activity is left here since it isn't the subject
public class MyClass implements MyThread.CallbackListener{
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
new MyThread(this).start();
//Your codes that do not require synchronization with the above thread
}
@Override
public void onObjectUpdated(Object obj){
//Your code that needs to be synchronized. In your case display your object here
}
}
而您的 MyThread class 将是
public class MyThread extends Thread{
Object obj;
CallbackListener listener;
public MyThread(CallbackListener listener){
this.listener = listener;
}
public void run(){
while (true) {
// update obj
listener.onObjectUpdated(obj);
}
}
public interface CallbackListener{
void onObjectUpdated(Object obj);
}
}
我们在这里所做的只是在对象更新后进行方法调用。
当对象更新后,您在 MyClass 中的 onObjectUpdated 方法将被调用,以使您的代码同步。您可以将任何非同步代码放入 onCreate 方法本身。