简体   繁体   English

等待UI线程在Android中完成操作

[英]Waiting for UI Thread to finish operation in Android

I am in this situation in my onCreate() method:我在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();

}

The problem here is that the update operation is not synchronized with the display operation: I always end up skipping a value because obj is updated before the UI thread is able to show its old value.这里的问题是更新操作与显示操作不同步:我总是跳过一个值,因为obj在 UI 线程能够显示其旧值之前更新。

What is the correct way to wait for the UI Thread to finish its job of displaying obj and only then proceed to the next iteration?等待 UI 线程完成其显示obj工作然后才进行下一次迭代的正确方法是什么?

You can use a callback here您可以在此处使用回调

Like,像,

//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
    }
}

And your MyThread class will be你的MyThread类将是

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);
    } 
}

What we are doing here is just making a method call when the object has updated.我们在这里所做的只是在对象更新时进行方法调用。

When the object has updated, your onObjectUpdated method in MyClass will be called so that making your code synchronized.当对象更新时,您在MyClass 中onObjectUpdated方法将被调用,以便使您的代码同步。 And you can put any non-synchronized code in the onCreate method itself.您可以将任何非同步代码放在onCreate方法本身中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM