Prevent activity from being destroyed as long as possible

前端 未结 2 2071
别那么骄傲
别那么骄傲 2020-12-06 16:38

I have an app, a single activity app with fragments in it.

The usual use case for this app is, that you start it and put the phone away and every now and then, you g

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 17:03

    don't keep your app in memory

    You don't want to block Android from killing your app. What you want is to restore your app's state properly. Then the user will never notice the app has been destroyed and the user still gets the benefit of an app that was destroyed when not in use.

    If you really want this use a wakelock. This will drain your users battery so I think twice before implementing this... Info at How do I prevent an Android device from going to sleep programmatically?

    onSaveInstanceState explained

    To do so check what information is needed in the bundle and persist that information with the onSaveInstanceState(bundle:Bundle) method so you can reuse it in onCreate(sameBundle:Bundle).

    More information available from Google documentation at Save your Activity state and Restore your Activity State.

    About Android Activity lifecycle

    As stated by @prom85 in the comments below it's not guaranteed that the onSaveInstanceState method will be called because it's not part of the lifecycle. Workaround for this is using the onPause lifecycle hook to ensure your data is stored.

    More information at Android: onSaveInstanceState not being called from activity

提交回复
热议问题