Android AsyncTask context behavior

前端 未结 4 2033
轮回少年
轮回少年 2020-12-23 17:11

I\'ve been working with AsyncTasks in Android and I am dealing with an issue.

Take a simple example, an Activity with one AsyncTask. The task on the background does

4条回答
  •  鱼传尺愫
    2020-12-23 17:34

    If you only need a context and won't use it for ui stuff you can simply pass the ApplicationContext to your AsyncTask.You often need the context for system resources, for example.

    Don't try to update the UI from an AsyncTask and try to avoid handling configuration changes yourself as it can get messy. In order to update the UI you could register a Broadcast receiver and send a Broadcast.

    You should also have the AsyncTask as a separate public class from the activity as mentioned above, it makes testing a lot easier. Unfortunately Android programming often reinforces bad practices and the official examples are not helping.

提交回复
热议问题