2

我的问题是......如果我们尝试在 startActivity() 之后执行一些代码,我们会在调用当前 Activity 的 onPause() 之前完全执行吗?也就是说,我不知道当包含它的方法到达末尾时是否会实际调用 startActivity() (方法发生的事情finish())。

我有一个示例,其中我想要detach()一个对象(具有数据库连接)后基于某些条件启动一个新的活动,但我需要这个对象来评估一个条件。我知道我可以检查该条件并将布尔值存储detach()在第一个之前if,但我想知道以下代码是否“合法”。

谢谢!

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();
}
4

3 回答 3

5

任何你想在调用到的方法中执行的东西都将在你收到对 的调用之前startActivity()被执行。问题是,您的应用程序默认使用一个主线程,调用和其他生命周期方法发生在其上。因此,当该线程忙于执行您方法中的代码时,它无法处理其他任何内容。onPause()onPause()

如果您的方法在其他线程中执行,这只会是一个问题。然而事实并非如此,因为这个方法是用来监听 UI 事件的,所以我假设它总是从主线程调用。

于 2012-03-08T14:57:48.723 回答
3

快速浏览 Android 源代码表明,如果您的代码在主事件线程上执行(在您的情况下看起来是真的),那么是的,它将在调用 onPause() 之前完成执行。

但是,我建议不要执行可能需要超过几毫秒才能完成的代码,因为这可能会影响应用程序在转换到下一个活动时的响应能力。

于 2012-03-08T14:57:35.493 回答
1

主事件循环,即 UI 线程不仅处理触摸事件,还处理活动生命周期回调,当一个新活动启动时,活动生命周期回调 onCreate()、onStart()、onResume() 被添加到事件队列等待轮到他们了,触摸事件也被添加到同一个事件队列中,所有代码都在单个主线程中执行。

明白当我们在代码中调用 startActivity() 时,activity 回调 onCreate(), onStart(), onResume() 或推入主事件队列,直到队列中前面的方法执行完毕后才会执行,所以下一个活动不会立即开始,而是将活动回调放入队列中,这些回调仅在执行当前方法后执行,即 startActivity() 之后的代码,当加载下一个活动时,当前活动的 onPause() 被推送进入队列。

如果您查看活动生命周期 图像链接onPause 在加载另一个活动时被调用

于 2016-07-21T07:09:55.367 回答