Friday, October 15, 2010

Android app lifecycle or "why do I sometimes get an empty screen?"

 

Many examples on the net for Android programs use something like this:

  public class MyActivity extends Activity {
    protected void onCreate(Bundle savedState) {
         super.onCreate(savedState);
         doSomeSetup(); // e.g. login to a remote site
dispatchToOtherActivity();
   }
}

This is usually fine, but in some situations you end up with an application that just shows an empty screen. You may wonder what happens here.

Actually if you have a look the Android Application Lifecycle , you will see that onCreate() will only be called when the application is 'cold started'.

If the application is just resumed, onCreate() is not called again and and thus the dispatch to the next activity never happens. The application just sits on the empty screen.

There is an easy solution: onResume() is always called when the application comes to foreground again no matter if the app was cold started or just came to foreground again. So the above code could also read:

public class MyActivity extends Activity {
   protected void onCreate(Bundle savedState) {
         super.onCreate(savedState);
         doSomeSetup(); // e.g. login to a remote site
   }
protected void onResume() {
         super.onResume();
         if (!loggedIn()) 
                doSomeSetup()
         dispatchToOtherActivity();
}
}

Now on cold start, the login is done in onCreate() and then control goes to onResume() that dispatches to the next activity. On warm start, onResume() is directly called, that can check if the login is still valid.

 

No comments: