In my app I have a MainActivity and a TimerActivity.
In normal circumstances in TimerActivity the device back button and the ActionBar's up button work as they should - they lead from the TimerActivity to the MainActivity. But when I open the TimerActivity by clicking on my app's notification, the back buttons lead to the home screen instead of the MainActivity.
I would like both back buttons (device and ActionBar's up button) to always open the MainActivity - unless of course the user is in the MainActivity in which case the back button should close the MainActivity. This is how Gmail and Google Drive apps work when you open an activity through a notification and it makes the most sense.
Here's how my notification opens the activity:
Notification timerNotification;
mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(ongoingNotificationIcon)
.setContentTitle(ongoingNotificationContentTitle)
.setContentText(ongoingNotificationContentText)
.setTicker(ongoingNotificationTicker)
.setPriority(99)
.setOngoing(true);
Intent resultIntent = new Intent(this, TimerActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
this, 0, resultIntent, PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
timerNotification = mBuilder.build();
startForeground(MyApplication.NOTIFICATION_ID, timerNotification);
I tried overriding the back button in TimerActivity like this:
public void onBackPressed() {
Intent intent_main = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent_main);
}
But then pressing the back button again on the MainActivity returns the user to the TimerActivity (so the user is in a loop) instead of exiting the app which is the desired behavior. Also, onBackPressed()
doesn't affect the ActionBar's up button.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…