我应该在一个长期运行的AsyncTask的使用getApplicationContext或Activity.thisgetApplicationContext、AsyncTask、this、Activ

2023-09-12 11:04:51 作者:關於伱、莪選擇沉默

我有一个长期运行的异步任务,发送一些数据到我的服务器,然后停止。整个过程可能需要几个请求和响应。我需要从数据库中读取数据,发送和处理响应,并相应地更新我的数据库。我使用的内容提供商读取和更新数据库数据。

I have a long running Async Task that sends some data to my server and then stops. The whole process may involve a few requests and response. I have to read data from database, send it and handle the response and update my database accordingly. I am using content providers to read and update data from database.

现在使用的内容提供商,我必须调用上下文的 getContentResolver()方法。所以,我想知道我是否必须使用 getApplicationContext 或只是通过 Activity.this 我的方法。

Now to use the Content Provider, I have to call the getContentResolver() method on context. So I am wondering whether I have to use getApplicationContext or just pass the Activity.this to my methods.

我看了几个帖子like这解释两部分,而大部分的区别,他们劝告我们不要使用 getApplicationContext 如果可能的话。虽然我不希望我的的AsyncTask 失去从 Activity.this 活动的背景下被破坏,或当方向变化。所以我想知道如果我可以使用 getApplicationContext 在我的情况下,还是会使用 Activity.this 符合我的要求。

I saw a few posts like this explaining the difference between the two and in most of them they advice us to not use getApplicationContext if possible. Although I do not want my AsyncTask to lose the context from Activity.this when the Activity is destroyed or when orientation changes. So I am wondering if I can use getApplicationContext in my case or will using Activity.this fit my requirement.

推荐答案

还有一个原因使用每个选项。

There is a reason to use each of the options.

当您,您使用的背景下,以修改UI应使用的应用程序上下文可能会导致异常使用活动的背景下,因为在某些情况下(