Somehow I cant use the GUI before the AsyncTask finished. I didn’t recognize any difference between posting the execute() in “onCreate” or “onCreateOptionsMenu” method.
Do you know what’s wrong?
Thanks for any help.
package com.test11;
import java.util.concurrent.ExecutionException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class TestActitivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_actitivity);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_test_actitivity, menu);
try
{
int t = new TestTask().execute().get();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
return true;
}
class TestTask extends AsyncTask<Void, Void, Integer>
{
public Integer doInBackground(Void...voids)
{
try
{
Thread.sleep(10000);
}
catch(Exception e)
{
e.printStackTrace();
}
return 1;
}
}
}
You execute your task like this:
What do you do exactly here? You create a new task instance. Then you run it. And then you call
get()on your task, which waits until the computation of this task is completed to return it’s value. Which means thatonCreate()oronCreateOptionsMenu()are blocked until the second thread is finished. If you removeget(), your task won’t block the UI.If you want to work with your result, you should override
onPostExecute()in your AsyncTask instead of usingget().onPostExecute()runs in the UI thread and allows you to use the result to manipulate the UI easily. If you want to display your result in a textview for example, you would use an implementation like this: