android: when to use onStart(), onStop()?

后端 未结 3 1689
悲&欢浪女
悲&欢浪女 2020-12-15 05:58

I\'ve read several posts that describe the difference between onStart() and onResume(): onStart() is called when the activity becomes

相关标签:
3条回答
  • 2020-12-15 06:30

    i think that your question is pretty explained here on the doc : read about the Activity Life Cycle

    0 讨论(0)
  • 2020-12-15 06:32

    onStop() will (for example) be called when you leave the activity for some other activity (edit: almost. see commonswares comment about dialog themed activities). For example if you use startActivity() in activity A to start activity B. When you press back in activity B you will return to activity A and onStart will be called.

    This differs from some of the reasons onPause might be called without onStop being called. If for example the screen times out or you press the standy button onPause will be called, but probably not onStop (depending on memory available and whatnot), so it is a "lighter pause". onStop will be probably be called eventually even in this case, but not immediately.

    Ok, but what's the use

    Often there is no specific use, but there might be. Since your activities will keep its memory state on the stack even after you start some other activity, that stack will increase with the number of activities started (height of the stack). This can lead to large memory usage in some applications. After a while the framework will kick in and kill some activities on the stack, but this is rather blunt and will probably mean a lot of states to be retained when returning.

    So an example use for onStart/onStop is if you want to release some state when leaving an activity for another and recreate it when you get back. I have used it to set listadapters to null, empty image caches and similar (in very specific applications). If you want to free the memory used by visible views in a listadapter you can recreate it in onstart and let the views be picked up by the gc. This will increase the likelyhood that the rest of the memory state of the activity will live on.

    Some resources can be deemed good enough to save while the activity instance is alive and some only when it is on the front of the stack. It is up to you to decide what is best in your application and the granularity of create/start/resume gives you that.

    0 讨论(0)
  • 2020-12-15 06:41

    onStart() works after onCreate() ended its task. It's a good place to put a broadcastReceiver or initialize some state about the UI that should display consistently anytime the user comes back to this activity.

    onResume() works when you come back to your Intent or Activity by pressing the back button. So onPause will be called every time a different activity comes to the foreground.

    0 讨论(0)
提交回复
热议问题