简体   繁体   中英

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.

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.

when an inner classes access private members (fields or functions) of the enclosing class, the compiler will generate accessor functions to those members. this will be breaking of encapsulation, some argue if it is a Good Thing or a Bad Thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM