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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With