Question

I have a requirement to run a long task on the launch of my main activity, I have to put it in the onCreate() method rather than onResume() as I only want it to run once not every time the Activity gains focus (ie from a dialog closing).

The issue is that the Layout does not display until the long running task completes and just leaves the app showing a black screen.

I thought that perhaps kicking it off in another Thread as follows would suffice but it appears the main thread still waits for this to complete before continuing with the layout?

final Thread launcherThread = new Thread(new Runnable() {
     @Override
     public void run() {
          doLongTask();
     }
});
launcherThread.start();

Any help would be appreciated thanks in advance.

If it helps the entire onCreate() is as follows:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inc_menu = (MenuContainer) this.getLayoutInflater().inflate(R.layout.main, null);
        setContentView(inc_menu);
        final Thread launcherThread = new Thread(new Runnable() {
             @Override
             public void run() {
                   doLongTask();
             }
        });
        launcherThread.start();
    }
Was it helpful?

Solution

it should be

launcherThread.start();

otherwise the Runnable will be executed in the context of the thread that called the run method.

Also

 inc_menu = (MenuContainer) this.getLayoutInflater().inflate(R.layout.main, null);
 setContentView(inc_menu);

can be changed in

 setContentView(R.layout.main);

There is not apparently reason to use an inflater in this case.

OTHER TIPS

You have mistake. When you call Thread.run() in start in same thread, that's why your interface not drawing. Replace it to Thread.start(). It will start new thread and UI will no blocked.

Prefer using the AsyncTask when programming for Android.

new AsyncTask<Void,Void,Void>(){
    @Override
    protected Void doInBackground(Void ... params){
        doLongTask();
        return null;
    }
}.execute();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top