2016-04-25 8 views
0

に隙間を実行するが、問題は、それは同じスレッドでdoOtherStuffを実行し、それは、UIスレッドで実行する必要があるということです。どうすればこれを達成できますか?スレッディングAndroidのは、今私は</p> <pre><code>public void someStuff(){ new Thread(new Runnable() { @Override public void run() { //doing long task doOtherStuff(); } }).start(); } public void doOtherStuff(){ doEvenMoreStuff(); } </code></pre> <p>をやってるUIスレッド

私はスレッドを使用しています。そうでないとアプリがフリーズします。スレッドが終了するのを待つだけでdoOtherStuffが必要です。

答えて

1

はこれを試してみてください:

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

thisはあなたの活動です。

+0

、ありがとうそれは簡単なことだろう知りませんでした... – dec0yable

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

のベストプラクティスであればわからないかもしれませんが、あなたはこれを試すことができ

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

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

提案された回答はAsyncTask

doInBackgrounddoInBackground終了した後に、UIスレッド上で実行されます:あなたのUIは

onPostExecuteを凍結しないように、バックグラウンドスレッドで実行さそれはあなたのケースで役立つことができる2つの方法があります。ジェネリッククラスは、次のようになります。

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

た他のハンドラを使用する別の方法:contextはあなたのActivity

関連する問題

 関連する問題