Caumons Caumons - 1 year ago 59
Android Question

Can we execute code after startActivity() before it gets paused?

My question is... If we try to execute some code after startActivity() will it we fully executed before the onPause() of the current Activity is called? That is, I do not know if startActivity() will actually be called when the method that contains it reaches the end (something that happens with the


I have an example in which I want to
an object (that has a Database connection) after a new Activity is started based on some conditions, but I need this object to evaluate one condition. I know I could check that condition and store the boolean value and
it before the first
, but I would like to know if the following code is "legal".


protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
School selectedSchool = new School((Cursor)l.getItemAtPosition(position));
.putLong(DatabaseManager.SCHOOL_ID, selectedSchool.getIdOpenErp())
School.SchoolManager schoolManager = new School.SchoolManager(this);
Long[] sessionIdsOpenErpOfSelectedSchool = schoolManager.getSessionIdsOpenErp(selectedSchool);
if (sessionIdsOpenErpOfSelectedSchool.length > 0) {
if (schoolManager.isPreviousWorkingSchoolPresent()) { // line 10
Intent iParticipationManagement = new Intent(this, ParticipationManagement.class);
} else {
Intent iSelectExistingSession = new Intent(this, SelectExistingSession.class);
} else {
Intent iSelectNewSession = new Intent(this, SelectNewSession.class);
// The following line will be executed after one of the startActivity() methods is called...
// Is this legal? Or should I get the value from isPreviousWorkingSchoolPresent() (at line 10)
// before the first if and do the detach() there as well?

Answer Source

Anyhting you want execute in the method with the call to startActivity() will get executed before you receive a call to onPause(). The thing is, your application by default uses one main thread, calls to onPause() and other lifecycle methods happen on it. So while this thread is busy with executing the code in your method, it can't process anything else.

This would only be a problem if your method were executed in some other thread. This is not the case, however, since this method is used to listen to UI events, so I assume that it is always called from the main thread.