2016-07-15 171 views
0

我具有以下与活动A,B,C的情况下: A-> B-> C->甲重新启动活动,而不是重新创建[Android的]

在该最后的步骤(C-> A),我想重写C的onBackPressed,以便它重新启动活动A(不重新创建它)。我尝试下面的代码,但仍然调用A的onCreate()。我应该添加哪个标志?

public void onBackPressed() { 

    Intent intent=new Intent(C.this, A.class); 
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    startActivity(intent); 

} 

回答

0

的OnCreate将称为,这是正确的行为,下面是来自Google documentation

当您的活动被重建后,先前被破坏,可以恢复已保存的状态从捆绑系统通过你的活动。 onCreate()和onRestoreInstanceState()回调方法都会收到包含实例状态信息的相同Bundle。

因为无论系统是在创建活动的新实例还是重新创建前一个实例,都会调用onCreate()方法,您必须在尝试读取之前检查状态Bundle是否为null。如果它为空,那么系统正在创建一个活动的新实例,而不是恢复之前被销毁的实例。

但如果处理得当,比如这并不重要:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); // Always call the superclass first 

    // Check whether we're recreating a previously destroyed instance 
    if (savedInstanceState != null) { 
     // Restore value of members from saved state 
     mCurrentScore = savedInstanceState.getInt(STATE_SCORE); 
     mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL); 
    } else { 
     // Probably initialize members with default values for a new instance 
    } 
    ... 
} 
0
public void onBackPressed() { 

    Intent intent=new Intent(C.this, A.class); 
    // remove below Flag and while going from A dont call finish(); 
    //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    startActivity(intent); 

} 
0

所以你要确保,该活动一个处于相同的状态,因为它是在切换到活动B之前,对吗?

您是否尝试过使用的onSaveInstanceState()/onRestoreInstanceState()(分别的onCreate(捆绑savedInstanceState))回调中所述:https://developer.android.com/training/basics/activity-lifecycle/recreating.html? 这里的示例:https://stackoverflow.com/a/151940/3540885

我不确定您希望的方式是否可行。通常最好让Android自己处理生命周期。只需要保存重要的东西只要系统感觉就像摧毁你的活动 - 这样你就可以再次与最后的状态重新创建...

编辑: 这是很久以前了,因为我最后一次与多个活动搞砸左右。你有没有考虑使用片段而不是多个活动?一旦我得到碎片的概念,我开始只使用一个父活动并替换碎片。因此,所有“沉重的东西”都可以在父活动中实例化一次,并由需要它的片段访问。这可能是一种替代解决方案,这是恕我直言值得思考的。

+0

是的,我想,以确保A是在相同的状态,因为它切换到B之前,但有一个理由。活动A的onCreate()正在做一些应该只执行一次的很重的东西,所以我想避免因为功耗而重复它。 –

+0

我仍然认为你应该使用Bundle“savedInstanceState”。 **“重物”** GUI相关吗?你可以提取逻辑,并在别的地方(也许应用程序类)做? – AZOM

+0

是的,它与GUI有关。我会探讨你的建议。 –

0

这是刷新活动的最佳方式:

public void refresh() { 
    Intent intent = getIntent(); 
    overridePendingTransition(0, 0); 
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 
    finish(); 
    overridePendingTransition(0, 0); 
    startActivity(intent); 
    } 
相关问题