2016-04-25 199 views
0

执行无效,现在我做线程Android在UI线程

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

public void doOtherStuff(){ 
    doEvenMoreStuff(); 
} 

但问题是,它在同一个线程执行doOtherStuff,它需要在UI线程中执行。我怎么能做到这一点?

我只使用线程,否则应用程序会冻结。我只需要doOtherStuff等待线程完成。

回答

1

试试这个:

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

this为您的活动。

+0

谢谢,不知道它会是这么简单...... – dec0yable

0

使用的处理程序:

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

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

其中context可能是你的Activity

0

不知道最好的做法,但你可以试试这个:使用处理器哪些其他的

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(); 
0

的另一种方式建议的答案是AsyncTask

它有两个方法可以是你的情况非常有用:

doInBackground:它会在后台线程中运行让你的UI不会冻结

onPostExecute:这之后doInBackground完成对UI线程上运行。泛型类可能看起来像:

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

,您可以通过执行任务:

new MyTask(inputs).execute()