If an activity is killed, does the AsyncTask live

2020-06-30 05:43发布

I think I know the answer to this, but does an AsyncTask continue to live on once its calling Activity has been finish()ed?

    protected void onPreExecute() {
        Toast.makeText(getApplicationContext(), "Your data is processing.", Toast.LENGTH_LONG);
        finish();
    }

Edit: so far two different answers :)

6条回答
Fickle 薄情
2楼-- · 2020-06-30 05:50

I've experienced some weirdness with Async Tasks where if an activity is killed by the OS and when the app resumes, the AsyncTasks sometimes do not run at all. I am unsure why they get into this state. If you execute your AsyncTasks in your own executor thread, this does not happen. I might be running into some odd circumstance. Thought it might be useful to post here anyway :).

查看更多
欢心
3楼-- · 2020-06-30 05:53

Async Tasks have no effect of the Activity lifecycle or any configuration changes. They keep on running till onPostExecute() method has been called.

One should use Services for long running operations instead.

查看更多
家丑人穷心不美
4楼-- · 2020-06-30 06:04

The AsyncTask is tied to a UI thread and if the Activity is finished the async task is canceled.

[update] - Hackbod's comment below is correct. It should be noted that AsyncTasks are meant to be short lived and as such not worry so much about this issue. An AsycTask is only truly gone when it is completed OR the process is killed which may or may not happen after finish is called.

查看更多
乱世女痞
5楼-- · 2020-06-30 06:04

Asynctask are not bounded to any life cycle method of Activity or Service.

It keeps running in a separate thread until the onPostExecute() gets executed in the main thread.

查看更多
Explosion°爆炸
6楼-- · 2020-06-30 06:10

Async task keeps running untill he onPostExecute() is finished.

try it by putting a toast on finish() and onPostExecute() to see which toast is shown first.

查看更多
戒情不戒烟
7楼-- · 2020-06-30 06:11

It keeps running until the onPostExecute finishes.

查看更多
登录 后发表回答