Android应用程序生命周期和后退按钮 [英] Android Application Lifecycle and back button

查看:168
本文介绍了Android应用程序生命周期和后退按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过关于活动的生命周期Android的文档。不过,我很好奇,在应用程序中是如何不同的活动行为。

I've read the Android Docs on the lifecycle of an activity. However, I am curious as to how different activities within an application behaves.

从一些测试,我已经做了,通过一个意图在同一应用程序内活动A过渡到活动B通过的onPause暂停活动A()并创建活动B通过的onCreate()

From some tests that I've done, transitioning from Activity A to Activity B within the same application via an intent pauses Activity A via onPause() and creates Activity B via onCreate().

奇怪的部分是,当活动B转换回活动A。

The strange part is when Activity B transitions back to Activity A.

如果硬件返回键是pressed,的onPause()被解雇活动B和 onResume()的活动A.被触发这是我所期望的那样。

If the hardware back key is pressed, onPause() is fired for Activity B and onResume() is fired for Activity A. This is what I would expect.

但是,如果在动作条是pressed后退按钮,的onDestroy()被解雇活动A,然后按的onCreate() onResume()

However, if the back button on the ActionBar is pressed, onDestroy() is fired for Activity A followed by onCreate() and onResume().

为什么会这样?

推荐答案

动作条被称为向上按钮中的返回按钮。这是向上按钮的预期行为,如果你看一下在code它执行的向上的实施,可以看到活动A被重建。

The "back button" on the ActionBar is called the "Up Button". This is the expected behaviour of the Up Button, if you take a look of the implementation of the code which performs the "up", you see that Activity A is recreated.

Intent parentActivityIntent = new Intent(getApplicationContext(), MainActivity.class);
parentActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(parentActivityIntent);
finish();

您可以定义什么是向上按钮应该做的,不过,我建议坚持默认行为

You can define what the "Up" button should do, however, I suggest to stick to the default behaviour.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // Your Code Here.
            break;
    }
}



为什么?

最多的按钮(与此相反的后退按钮)应导航一个级别更高的应用层次,始终。后退按钮应该去的的,即使它会离开当前应用程序。

你不能只是呼吁结束对当前活动,因为父活动可能已经被垃圾回收和Don' ŧ存在了。

The Up Button (in contrast to the back button) should navigate one level higher in the application hierarchy, always. The back button should go back, even if it will leave the current application.
You can't just call finish on the current Activity, because the parent Activity could already be garbage collected and don't exist anymore.

我大量建议阅读官方 Android设计准则,尤其是部分了解高达VS返回

I heavily suggest to read the official Android Design Guidelines, especially the part about Up vs Back.

这篇关于Android应用程序生命周期和后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆