简体   繁体   中英

Android AsyncTask and Thread life cycle

I am a little confused about AsyncTask and Thread life cycle. What happens to a processes threads when the OS enters the OnStart/OnStop and onResume/onPause sequences. Are the threads affected by this sequence. I ask this question because I am using sockets in the threads and killing the threads will kill the tcpip connections as well (I assume). If the thredas are not killed then how do I 'reconnect' to them especially as they may will be 'connected' to an activity via a Handler.

Threads are not automatically killed when the app goes to onStop or onPause, however, there is no guarantee it won't be killed. Android will keep it running until it needs the resources that the thread is using.

Generally, if you want a persistent connection when an Activity closes, then put that in a Service . You can run threads in it just like an Activity (to prevent blocking that usually occurs with connections), and it's far less likely Android will kill it.

Internally, AsyncTask uses fixed thread pool. (See http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html )

So, even if AsyncTask finished, thread does not die. But thread in thread pool can be killed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM