2016-04-25 198 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()