Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should Android data be committed/read in onPause() - onResume() rather than in onStop() - onStart()?

The documentation suggests that the data should be committed/read in onPause()/onResume().

Yet when the application is no longer in the foreground, its data structures remain intact, which suggests that one could delay committing/reading data until the application is no longer visible, i.e. in onStop()/onStart(). Particularly since onStop() is guaranteed to be called before onDestroy().

Is it perhaps the case that either approach is suitable? Is the documentation giving here merely a guideline?

Update Suppose your application needed to save relatively substantial data, say edits to a large image. One would then surely not write/read in onPause()/onResume(), lest the user experience become sluggish. One would in that case choose instead to write/read in onStop()/onStart(). Is that true?

like image 434
Calaf Avatar asked Jan 21 '26 21:01

Calaf


1 Answers

The problem with using onStop is that you have no guarantees on when it will be called since the only sure thing is that it will be called before onDestroy. If you wait until onStop to commit your data it may be to late for another activity to show/use any of those changes. Same thing applies to onStart, your activity may not need to be restarted if it was just in the background so you'll have stale data. Using onResume and onPause guarantees that your data will always be current, commits are made as soon as the activity goes to the background and new data is loaded as soon as it becomes visible.

like image 74
ebarrenechea Avatar answered Jan 24 '26 09:01

ebarrenechea