按下后退按钮时如何终止活动? [英] How do I kill an Activity when the Back button is pressed?

查看:33
本文介绍了按下后退按钮时如何终止活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动,当它启动时,它会从互联网加载一张图片.为了节省内存,当按下后退按钮离开活动时,我希望活动转储所有数据,即摆脱其中的所有字符串和图像.我认为最好的方法就是终止活动.

I got an Activity that when it starts, it loads an image from the internet. In an effort to save memory, when the Activity is left by the back button being pressed, I want the activity to dump all data, that is get rid of all the strings and images that are in it. I figured the best way to do this was to just kill the activity.

好吧,我似乎无法弄清楚按下后退"按钮时的回调.所以,我一直在尝试使用 onPause()onStop() 回调来完成任务,但两种方式都强制关闭我的应用程序.代码如下:

Well, I can't seem to figure out the callback for when the Back button is pressed. So, I have been trying to use the onPause() and the onStop() callbacks for the task but both ways force close my app. Here is the code:

public void onPause() {
    this.finish();
}
public void onStop() {
    finish();
}

我已经尝试了多种变体,但它们似乎都不起作用.有任何想法吗?

I've tried multiple variations of this, but none of them seemed to work. Any ideas?

推荐答案

将此添加到您的活动

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK))
    {
        finish();
    }
    return super.onKeyDown(keyCode, event);
}

这篇关于按下后退按钮时如何终止活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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