简体   繁体   English

内部AsyncTask安全访问外部Activity类私有成员字段?

[英]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()? 对于Android AsyncTask来说,在AsyncTask.doInBackground()中读取Activity的私有成员字段是Activity的内部类是否安全? 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.). 理想情况下, AsyncTaskdoInBackground()应该能够独立于其启动组件(活动,服务等)运行。 I suggest that you create a constructor on your AsyncTask and pass in whatever is needed. 我建议你在AsyncTask上创建一个构造函数,然后传入所需的东西。 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. 或者,让AsyncTask由使用setRetainInstance()的动态片段管理,在这种情况下(AFAIK),任务访问片段的私有数据成员应该是安全的,因为片段不会去任何地方。

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. 这将破坏封装,有些人认为这是好事还是坏事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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