通过静态类传递上下文是否有效?
在android中,我需要引用“上下文”或者说将“上下文”传递给几个类。为此,我实现了一个静态类,它保存“上下文”以及通过它的所有其他类访问上下文。
//let's say I have a static class DataHolder
//and my main acitivity i.e. whose context need to be refrenced
public class DataHolder{
public static Context context;
}
public class MainActivity extends Activity{
public void onCreate(Bundle bundle){
DataHolder.context = getApplicationContext();
}
}
那么,这个过程是否可以实现,或者它不是在Android应用程序中引用的正确方法。
In android, I need reference "context" or to say pass "context" to several classes. For this purpose I have implemented a static class which holds the "context" and all other class access context through it.
//let's say I have a static class DataHolder
//and my main acitivity i.e. whose context need to be refrenced
public class DataHolder{
public static Context context;
}
public class MainActivity extends Activity{
public void onCreate(Bundle bundle){
DataHolder.context = getApplicationContext();
}
}
So, is this process ok to be implemented or it is not the right way to reference in Android application.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里的问题不在于效率,而在于静态存储上下文的固有风险。
上下文在许多事件中都可能发生变化,最有可能的一个是改变设备方向,因此您不应该总是依赖它。我认为您应该将构造函数中的 Context 传递给您认为会使用它的每个类(或者,更确切地说,重新设计您的代码,以便在它不可用的地方不需要它,尽管这可能有点棘手)。
在最坏的情况下,您应该尝试尽可能频繁地更新它。但是,话又说回来,让它始终可访问有什么意义呢?我认为,为了进行仔细的应用程序设计而冒的风险不值得(抱歉,如果这听起来很粗鲁,我不是故意的)。
The issue here is not about efficiency, but about the inherent risks of storing your context statically.
The context can change in many events, the most likely one is changing the device orientation, so you shouldn't relay on it always. I think you should pass the Context in the constructor to each class you think would use it (or, rather, redesign your code so you don't need it where it's not available, although this may be a bit tricky).
In the worst case scenario, you should try to update it as frequently as you can. But, then again, what's the point in having it always accessible? I think the risks are not worth the laziness (sorry if it sounds rude, I don't mean it to) of making a careful app design.
你应该绝对避免它,因为它可能会导致内存泄漏。
阅读:避免内存泄漏
You should definetely avoid it, since it may lead to a memory leak.
Read: Avoiding memory leaks