菜鸟的安卓实习之路---如退出应用程序

如何正确的退出应用程序?

1 最初的方案,是建立一个activity 的栈,每当有一个新的activity onCreate() 的时候,就把他加入到这个栈中,在希望退出的时候,将栈中的activity 们全部finish()掉就可以了。

这样可以实现,但是activity栈,我们来管理,可能会出现内存泄露的情况,所以,在大神的劝导下,改为方案二,方案二来自美帝的stackOverflow .


方案二: 

基本思路: 在希望退出应用程序的时候,回到应用程序的入口activity ,在使用如下的方法: 

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
<strong>intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);</strong>
intent.putExtra("EXIT", true);
startActivity(intent);
上面的代码,clear 了除了loginActivity 以外的全部activity, 因为在android ,activity 栈结构中,第一个activity 是被压在最下面的。将它上面的activity门全部清掉,就只剩下自己了。

接着在loginActiviy 的oncreate()中:

if (getIntent().getBooleanExtra("EXIT", false)) {
    finish();  
}


3 为什么android 不鼓励用一个按钮来退出整个应用程序? 

The Android OS developers want your program to be able to survive an unexpected shutdown and power off of the phone, and when the user restarts the program, they pick up right where they left off. So the user can receive a phone call while they use your application, and open maps which requires your application to be freed for more resources.

When the user resumes your application, they pick up right where they left off with no interruption. This exit button is usurping power from the activity manager, potentially causing problems with the automatically managed android program life cycle.

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值