Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe for inner AsyncTask to access outer Activity class private member fields?

Is it safe for an Android AsyncTask that's an inner class of an Activity to read the Activity's private member fields while in AsyncTask.doInBackground()? Thanks in advance.

like image 438
Julian A. Avatar asked Jan 16 '12 17:01

Julian A.


1 Answers

Generally, no. If the activity is undergoing a configuration change and is being destroyed and recreated, your background thread will be talking to the wrong instance, which may cause problems for you.

Ideally, the doInBackground() of an AsyncTask should be able to run independently of its launching component (activity, service, etc.). I suggest that you create a constructor on your AsyncTask and pass in whatever is needed. Or, have the AsyncTask be managed by a dynamic fragment that uses setRetainInstance(), in which case (AFAIK) it should be safe for the task to access private data members of the fragment, since the fragment is not going anywhere.

like image 162
CommonsWare Avatar answered Oct 30 '22 23:10

CommonsWare