Should I use getApplicationContext or Activity.this in a long running AsyncTask

后端 未结 1 1883
长情又很酷
长情又很酷 2020-12-01 01:16

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 databa

相关标签:
1条回答
  • 2020-12-01 01:59

    There is a reason to use each of the options.

    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());
    

    When you are using the context in cross-activity usage, you should not bind 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.

    If you are only using the context to call getContentResolver, you should use the Application context.

    0 讨论(0)
提交回复
热议问题