如何使活动停止,而不是被破坏,从BACK键? [英] How to make an activity stop, rather then be destroyed, from the BACK key?

查看:137
本文介绍了如何使活动停止,而不是被破坏,从BACK键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在的活动被破坏时,BACK键为pressed。我怎样才能使它只是停止(即保留所有的变量,等活的),而不是被破坏?

Right now an activity gets destroyed when the BACK key is pressed. How can I make it just stop ( i.e. keep all the variables, etc. alive ), rather then be destroyed?

谢谢!

推荐答案

为什么你需要保持的变量还活着吗?鉴于Android应用程序的生命周期建立的,我不知道是$ P $遭受破坏只是为了保持变量有道理pventing活动。

Why is it that you need to keep the variables alive? Given the established lifecycle of an Android application, I'm not sure that preventing the activity from being destroyed "just to keep the variables" makes sense.

  1. 即使停止应用程序,而不破坏它,总是有机会的机器人会杀死它来释放内存。你必须考虑到这一点在你的code,无论如何,所以$ P $毁坏pventing应用程序不救你写入code。

  1. Even if you stop the application without destroying it, there is always the chance that Android will kill it to free up memory. You will have to account for this in your code anyway, and so preventing the application from destroying doesn't save you from writing code.

变量可以被保存和恢复比较方便,快捷地使用共享preferences在你的onPause()和onResume()方法。除非你存储大量的数据,$ P $毁坏pventing的应用程序可能没有多大的差别。

Variables can be saved and restored relatively easily and quickly using SharedPreferences in your onPause() and onResume() methods. Unless you are storing a ton of data, preventing the application from destroying might not make much of a difference.

这听起来像你想要的,因为你打算回到这个活动,以保持在内存中的变量。通常情况下,您不使用后退按钮浏览远离你打算回来的活动。相反,你将创建一个意向,并开始一个新的活动。执行此操作时,机器人放置在返回堆栈的当前活动调用的onPause()和的onStop(),这似乎是你正在寻找的行为完全排序。

It sounds like you want to keep the variables in memory because you intend to return to this activity. Typically, you don't use the back button to navigate away from activities that you intend to come back to. Instead you would create an Intent and start a new activity. When you do this, Android places the current activity on the Back Stack calling onPause() and onStop(), which seems like exactly the sort of behavior you are looking for.

所以,如果你还是真的想prevent被破坏(至少要等到Android的决定是占用了过多内存,并杀死它在它自己),你总是可以使用萨格尔的code和开始新的活动在onBack pressed活动()。

So if you still really want to prevent your activity from being destroyed (at least until Android decides it's using too much memory and kills it on it's own) you could always use Sagar's code and start a new activity in onBackPressed().

@Override
public void onBackPressed()
{
    Intent intent = new Intent(this, Other.class);
    startActivity(intent);       
}

只是可以肯定,这是你真正想做的事情。

Just be certain that that is what you really want to do.

这篇关于如何使活动停止,而不是被破坏,从BACK键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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