【问题标题】:Android: How to kill the current activity if the new activity is the same with the current one?Android:如果新活动与当前活动相同,如何杀死当前活动?
【发布时间】:2016-04-26 00:24:08
【问题描述】:

我知道这个问题有点难理解,我是 Android 新手,我的意思是:

假设我有一个当前处于活动状态的活动 A,然后我让设备进入睡眠状态并唤醒设备,活动 A 现在仍然处于活动状态。

此时会弹出一个对话框,我按“是”,将创建一个新的活动A。我关心的是,我如何杀死旧的 A 然后创建新的 A?

现在当我点击“是”时,新的 A 已创建,但显示不正确。

【问题讨论】:

  • 为什么你想要解决而不是试图找到问题 -> Right now when I click "Yes" the new A is created but it's not showing correctly.not showing correctly 是什么意思?
  • 一开始为什么要这样做?已经存在的 Activity A 有什么问题?
  • @Karakuri 当用户什么都不做并且设备稍后会自动休眠时会发生这种情况。当用户唤醒设备时,fragment 上的内容应该会被刷新。
  • @MarcinOrlowski 它没有正确显示,因为片段没有重新创建,这是由于我唤醒设备并停留在这个片段上造成的。
  • @Zip 没关系,你不需要杀死 Activity 并显示一个新的,你只需要更新 UI。您可以使用生命周期回调来执行此操作,例如 onStart()(在 Activity 或 Fragment 中)

标签: android android-activity fragment


【解决方案1】:

我不确定要达到什么目的,但是这段代码 sn-p 应该可以满足您的要求。

finish();
Intent intent = new Intent(this, YourActivity.class);
startActivity(intent);

另一种选择是调用

recreate();

正如documentation 所说:这导致与由于配置更改而创建 Activity 时基本相同的流程——当前实例将经历其生命周期到 onDestroy() 并在其后创建一个新实例。”

【讨论】:

    【解决方案2】:

    试试这个,希望这会有所帮助。

    Intent intent = new Intent(this, yourclass.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    finish();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多