当您按下返回按钮时,Android会返回上一个活动,但在您的位置没有最后一个活动,因为您直接启动了RidesActivity。
要解决此问题,您可以通过通知中的Intent而不是您的RidesActivity启动MainAcivity,并将一些额外的信息直接启动RidesActivity。
代码为您的通知:
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //is important to start the activity from a notification
intent.putExtra("startRidesActivity", true);
startActivity(intent);
代码为您的MainActivity,onCreate方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* Put the following at the end of this method
*/
Bundle bundle = getIntent().getExtras();
if(bundle!=null && bundle.containsKey("startRidesActivity")){
Intent intent = new Intent(this, RidesActivity.class);
startActivity(intent);
}
}
就是这样。现在你的通知打开MainActivity,MainActivity直接开始你的RidesActivity。如果你点击后退按钮,你应该看到你的MainActivity,而不是你的主屏幕。
很好的答案!非常感谢。只是所以我知道,为什么从通知开始活动时添加NEW_TASK标志很重要?在其他情况下,你需要把这个标志? –
这很重要,因为通知不会在您的应用程序的上下文中运行,并且Android需要此信息才能在“新任务”中启动您的应用程序。这里很好解释:http://stackoverflow.com/questions/30886618/android-notification-intent-flag-activity-new-task-required – Larcado
明白了。此外,如果我在应用程序中收到通知,并且我点击它 - 我将按照以下顺序执行活动:RidesActivity-> HomeActivity->正在运行的其他任何活动。我应该在点击通知时杀死所有其他活动吗? –