outsidethecave
outsidethecave

Reputation: 75

Waiting for UI Thread to finish operation in Android

I am in this situation in my onCreate() method:

@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.

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?

Upvotes: 1

Views: 1224

Answers (1)

user13608097
user13608097

Reputation: 76

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

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. And you can put any non-synchronized code in the onCreate method itself.

Upvotes: 3

Related Questions