0

right now i'm doing

public void someStuff(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            //doing long task
            doOtherStuff();
        }
    }).start();
}

public void doOtherStuff(){
    doEvenMoreStuff();
}

but the problem is that it executes doOtherStuff in the same thread and It needs to be executed in the UI Thread. how can I accomplish this?

I am only using the thread because otherwise the app freezes. I just need doOtherStuff to wait for the thread to finish.

4 Answers 4

1

Try this:

this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //do something
            }
        });

this is your activity.

Sign up to request clarification or add additional context in comments.

Comments

0

Use handler :

  public void doOtherStuff(){
    new Handler(context.getMainLooper()).post(new Runnable() {

        @Override
        public void run() {
          // Executes on UI thread
          doEvenMoreStuff();
        }
    });
  }

where context might be your Activity

Comments

0

Not sure if best practice but you can Try this:

public void someStuff(){
new Thread(new Runnable() {
    @Override
    public void run() {
      YourActivityClassName.this.runOnUiThread(new Runnable() {
          @Override
          public void run() {

           //doing long task
            doOtherStuff();
          }
      });

    }
}).start();  

Comments

0

An alternative way of using Handler which other answers suggested is AsyncTask:

It has two methods which can be useful in your case:

doInBackground: which runs in the background thread so your UI won't freeze

onPostExecute: which runs on UI thread after doInBackground finishes. A generic class may look like:

private class MyTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... input) {
      //do background processes on input and send response to onPostExecute
      return response;
    }

    @Override
    protected void onPostExecute(String result) {
       //update UIs based on the result from doInBackground
    }
  }

and you can execute the task by:

new MyTask(inputs).execute()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.