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.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 anAsyncTaskshould be able to run independently of its launching component (activity, service, etc.). I suggest that you create a constructor on yourAsyncTaskand pass in whatever is needed. Or, have theAsyncTaskbe managed by a dynamic fragment that usessetRetainInstance(), 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.