Prevent activity from being destroyed as long as possible

前端 未结 2 2066
别那么骄傲
别那么骄傲 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

    0 讨论(0)
  • 2020-12-06 17:05

    I had a similar problem, I arrived at this post while searching for a solution, you have to play with the manifest to achieve this and also understand what exactly activity is, in Android eco system,

    In Android activity is a task which has a pre defined work.

    I dig a lot in the documentation, I found that, we can configure activity in two ways,

    1. Persistent
    2. non persistent

    if you mention for the activity in the manifest as

    android:persistent="true"
    

    and run the below use case

    1. Start the APP
    2. Press back or home button
    3. you select the activity in the back stack again to bring it to front

    Activity enters start -> pause -> stop - > resume , it does not get into onDestroy method.

    if do not mention

    android:persistent="true"
    

    for the same use case

    Activity enters start -> pause -> stop -> destroy, and if you select the activity from the back stack

    Activity enters resume->create->start

    If you want to run a service/task on activity start which keeps running when the app is in back stack, then you have to start that in the onCreate method, and kill them onDestroy by specifying your activity as persistent in manifest.

    I hope my above solution might help others who arrive here for the same problem

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