Threading Android execute void in the UI thread

时间:2016-04-25 09:27:27

标签: java android multithreading

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 个答案:

答案 0 :(得分:1)

Try this:

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

this is your activity.

答案 1 :(得分: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

答案 2 :(得分: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();  

答案 3 :(得分: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()