简体   繁体   English

按下后退按钮时破坏活动?

[英]Destroy an activity when back button is pressed?

I have an app that allows user to select a txt file from a list and then goes off to the internet to get the contents of that file. 我有一个应用程序,允许用户从列表中选择一个txt文件,然后转到互联网获取该文件的内容。 All works well except when the user accidentally or deliberately presses the hardware back button to go and see the list again. 除非用户不小心或故意按下硬件后退按钮以再次查看列表,否则所有操作均正常。

Now, when the user clicks a new item from the list (a new file that is), instead of loading a the new file, the app continues off from where it was suspended.I do not want that to happen. 现在,当用户从列表中单击一个新项目(即一个新文件)时,该应用程序从挂起的位置继续运行,而不是加载新文件,我不希望这种情况发生。 I know this is related to the life cycle of the activity. 我知道这与活动的生命周期有关。

How do I make sure that it loads the new file rather than continuing from where it left off ? 如何确保它加载了新文件而不是从上次中断的地方继续?

I suppose you're loading the file in onCreate() . 我想您是在onCreate()加载文件。 You should do that in onResume() instead. 您应该改为在onResume()执行此操作。

Android应用生命周期

Do not force Activities to close (eg use finish() ). 不要强迫活动关闭(例如,使用finish() )。 First, this does not guarantee the Activity will be closed , and second, this is better left to Android to decide. 首先, 这不能保证Activity将被关闭 ,其次,最好由Android来决定。

您可以在活动中覆盖onBackPressed方法,然后调用finish()获得所需的结果。

您只需要通过调用activity.finish()在onBackPressed()方法中完成您的活动即可;

To destroy activity on back press, use this code. 要破坏背部按压时的活动,请使用此代码。

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
     //Destroys activity.
     finish();
}

Another Method to kill an activity is by calling following method. 杀死活动的另一种方法是调用以下方法。

@Override
public void onBackPressed() {
    super.onBackPressed();
    finish();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM