我应该在一个长期运行的AsyncTask的使用getApplicationContext或Activity.this [英] Should I use getApplicationContext or Activity.this in a long running AsyncTask
问题描述
我有一个长期运行的异步任务,发送一些数据到我的服务器,然后停止。整个过程可能需要几个请求和响应。我需要从数据库中读取数据,发送和处理响应,并相应地更新我的数据库。我使用的内容提供商读取和更新数据库数据。
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.
我看了几个帖子<一href="http://stackoverflow.com/questions/1026973/android-whats-the-difference-between-the-various-methods-to-get-a-context">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应使用的应用程序上下文可能会导致异常使用活动的背景下,因为在某些情况下(as 和<一href="http://stackoverflow.com/questions/4851394/getapplicationcontext-throws-an-exception-when-used">here).如在以下的情况:
When you are using the context in order to modify the UI, you should use the Activity context, since in some cases using the application context might cause an exception (as described here and here). Such as in the following case:
TextView senderNameTextView = new TextView(getApplicationContext());
当使用的是在交叉活性用法的情况下,应该没有结合活性的上下文的动作,从此之后,即使该活动被破坏,它不会是垃圾收集的,因为它仍从引用正在运行的任务。在这种情况下,你应该使用应用程序上下文。请参见文章中的Android开发者网站(写的罗曼盖伊)甚至更多详细信息
When you are using the context in cross-activity usage, you should not bound the Activity context to the action, since then even if the activity is destroyed, it will not be garbage-collected, as it is still referenced from the running task. In those cases, you should use the Application context. See the article in Android Developer's site (written by Romain Guy) for even more details.
如果您只使用上下文来调用 getContentResolver
,你应该使用的应用程序上下文。
If you are only using the context to call getContentResolver
, you should use the Application context.
这篇关于我应该在一个长期运行的AsyncTask的使用getApplicationContext或Activity.this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!