当我按下 MainActivity 上的后退按钮时,我希望我的应用程序关闭。目前,当我在 MainActivity 上按下它时,它会返回到以前的活动。
问问题
1063 次
3 回答
1
@Override
public void onBackPressed() {
YourActivity.this.finish();
}
值得注意的是,更改默认行为并不是一个好主意。
于 2016-02-03T16:00:40.550 回答
1
为什么您希望您的应用程序不返回以前的活动?如果您的 MainActivity 是由您不想返回的活动启动的,最好将标志添加到启动 MainActivity 的意图中,这样前一个活动就不会留在任务堆栈中。
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
如果您不想这样做,则必须覆盖 OnBackPress() 以删除/完成堆栈中 MainActivity 下的任务。例如,这可以通过 LocalBroadcaster 来完成,尽管它非常难看。
在您要关闭的活动中:
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("Your filter");
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
}
在您的 MainActivity 中:
@Override
public void onBackPressed() {
Intent intentBroadcast = new Intent("Your filter");
LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(intentBroadcast);
finish();
}
于 2016-02-04T06:28:10.480 回答
1
您可以使用 System.exit(0)。
@Override
public void onBackPressed() {
System.exit(0);
}
于 2016-02-03T16:14:27.053 回答