[英]How to exit an app when Back Button is pressed
This is a small question but I'm finding very hard to solve this.这是一个小问题,但我发现很难解决这个问题。 I have multiple activities.
我有多个活动。 For example AB and C. When app is launched A is opened and on click of button will redirect me to activity B and then from B on click of another button will take me to C. On Back pressed will now bring me back to B and again on Back button is pressed will take me to A which is main Activity.
例如 AB 和 C。当应用程序启动时,A 被打开,单击按钮会将我重定向到活动 B,然后从 B 单击另一个按钮会将我带到 C。按下后退现在会将我带回 B 和再次按下“后退”按钮会将我带到主要活动的 A。
Now if I press back button, instead the app should exit...it creates loop between B and A and never exit the app.现在,如果我按下后退按钮,应用程序应该退出......它会在 B 和 A 之间创建循环并且永远不会退出应用程序。
I already used the following method我已经使用了以下方法
Method 1: use of this.finish
onBackPressed which didn't help方法 1:使用
this.finish
onBackPressed 没有帮助
Method 2: use android:nohistory = true
in manifest方法二:在 manifest 中使用
android:nohistory = true
But If I do so then from C activity it will directly take me to A which I don't want.但是,如果我这样做,那么从 C 活动中它会直接将我带到我不想要的 A。
Method 2. Use of方法 2. 使用
Intent intent = new Intent(Intent.ACTION_MAIN);
//to clear all old opened activities
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
when I use this then everytime this opens up in my device当我使用它时,每次它在我的设备中打开时
Please anyone help.请任何人帮忙。
This is my code in Mainactivity now这是我现在在 Mainactivity 中的代码
@Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
But also it don't work and it creates loop between A and B Activity.但它也不起作用,它会在 A 和 B 活动之间创建循环。
Your code (in MainActivity) is incorrect , put finish() after super.onBackPressed()您的代码(在 MainActivity 中)不正确,将finish()放在super.onBackPressed() 之后
it must be :肯定是 :
@Override
public void onBackPressed() {
super.onBackPressed();
finishAffinity(); // or finish();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.