What happens to an Android thread after the Activity that created it is destroyed?

前端 未结 4 1888
一向
一向 2021-02-07 04:25

In my Android app, the main Activity will sometimes start a Thread to load data from a server. This thread modifies the app\'s database and edits some important files. AFAIK,

4条回答
  •  醉梦人生
    2021-02-07 05:29

    AFAIK, it would appear that this thread continues to execute.

    This is true but you have no guarantee of how long the thread will stay alive.

    What will happen to this thread if the Android gets into a low memory situation and decides to kill the entire Application?

    This is actually a fairly rare case in my experience but it will depend on the device's available memory and the user's behaviour, for example they use the device heavily and start multiple apps.

    Will there ever be a situation were this thread might die prematurely?

    Yes

    If so, is there any way I can see that the thread is being killed, and do something about it?

    No

    I'm asking because this thread modifies important data in the database, and if it is suddenly killed, the application could stop functioning properly.

    What you describe could be classed as something which is 'mission critical'. As the other two answers have pointed out, a Service would be a more robust way of doing things as a Service is one of the last things to be 'killed' in a low memory situation. Using START_REDELIVER_INTENT may help in resuming what it was doing.

    In any case, if you have a 'mission critical' operation, you need to design your code for full recovery such as the use of transactions and the possibility of rollbacks in case of errors.

提交回复
热议问题