我的問題是... 如果我們嘗試在startActivity()之後執行一些代碼,它會在調用當前Activity的onPause()之前完全執行嗎?也就是說,我不知道當包含它的方法到達結尾時(如果使用方法finish()
),startActivity()實際上會被調用。我們可以在startActivity()暫停之前執行代碼嗎?
我有一個例子,我想要在基於某些條件啓動一個新Activity之後創建一個具有數據庫連接的對象detach()
,但我需要此對象來評估一個條件。我知道我可以檢查該條件並將其存儲在第一個if
之前的布爾值和detach()
,但我想知道下面的代碼是否是「合法」的。
謝謝!
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));
mSharedPreferences.edit()
.putLong(DatabaseManager.SCHOOL_ID, selectedSchool.getIdOpenErp())
.commit();
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);
startActivity(iParticipationManagement);
} else {
Intent iSelectExistingSession = new Intent(this, SelectExistingSession.class);
startActivity(iSelectExistingSession);
}
} else {
Intent iSelectNewSession = new Intent(this, SelectNewSession.class);
startActivity(iSelectNewSession);
}
// 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?
schoolManager.detach();
}
是的,這個方法在UI線程裏面。我不確定對startActivity()的調用是否會「中斷」包含它的方法,並且由於onPause()會立即調用,因此不會執行下面的方法。但正如你所說,事實並非如此,因此我所做的「合法」。感謝您的答覆! :) – Caumons 2012-03-08 15:11:01
@Caumons只有當所有的生命週期方法調用實際發生在調用'startActivity()'的時候纔會發生。但是,情況並非如此,因此如果所有內容都來自同一個線程,則不能調用「onPause()」。 – Malcolm 2012-03-08 15:20:22