1

The title is self explanatory: I would like to know if a new activity can handle the onBackPressed() before the onCreate() is finished. In other words, at which point in the lifecycle is the handling of the soft back button touch transferred to a newly created activity?

Thanks in advance.

pmlnunes
  • 11
  • 1
  • 1
    Creating, attaching activity and onBackpressed are all invoked on main looper thread synchronously, I'm rather positive it's impossible to trigger any button/touch/keyboard callbacks before lifecycle chain of `onCreate` -> `onStart` -> `onResume` concludes. – Pawel Apr 23 '20 at 15:39
  • Would this mean that if the user presses the back button during the onCreate(), the onBackPressed() will be called after onResume() on the new activity? Or will it be called by the previous activity? – pmlnunes Apr 23 '20 at 15:56
  • 1
    You can do a quick test yourself by putting a `Thread.sleep` inside onCreate. I did that and what I got is key presses will be delayed until `onResume` finishes, then you will receive them in `onKeyDown`/`onKeyUp` methods with `KEYCODE_BACK` but `onBackPressed` itself will not be triggered. – Pawel Apr 23 '20 at 16:14
  • I get it now, thanks. But this created another question for me: if the main thread is doing some work and the user presses the back button, will the main thread be interrupted to deal with it? In other words, when can I expect the onBackPressed() to be called? At any time? – pmlnunes May 06 '20 at 13:29

1 Answers1

0

onBackPressed() will not get initiated until the activity has been started, i.e. after the onResume() has finished. This happens because activity needs to be literally in the front, that is at the top of the stack and active on the screen for the back press to happen. You will not be able to initiate onBackPressed() in before or after the onCreate() in an activity's lifecycle.

Karan Dhillon
  • 1,186
  • 1
  • 6
  • 14