将 Context 传递给构造函数并将其保存为私有变量以供内部使用是不好的做法吗?另一种选择是将 Context 作为参数传递给需要它的方法。
哪个是更好的选择?我有一种感觉,传递给构造函数可能会意外导致内存泄漏。
将 Context 传递给构造函数并将其保存为私有变量以供内部使用是不好的做法吗?另一种选择是将 Context 作为参数传递给需要它的方法。
哪个是更好的选择?我有一种感觉,传递给构造函数可能会意外导致内存泄漏。
Often, all you need is the ApplicationContext
, so what you can do is pass this.getApplicationContext()
instead of just this
. Your app context exists for the lifetime of the app anyway, so it's not a memory leak.
这取决于对象的生命周期。如果您确定 Object 只会在您的 Activity 内部使用,则可以将 Context 传递给构造函数,否则不要将 Context 传入。
如果一个对象引用了上下文,这将停止 Activity 被垃圾收集,并且由于一个 Activity 引用了它的所有视图,这意味着你可以很容易地很快泄漏大量内存。
在这里很容易发现自己,因为诸如设备旋转之类的事情会导致重新创建活动,并且很容易在没有意识到的情况下挂在对象上。
因此,最好是在安全方面并在需要时传递 Context 。
In the main application (which launches), declare a variable appContext: "public static Context appContext;" Then, in the onCreate() method for this main application, assign: "appContext = this;" Because appContext is public, any other class in this package can then use appContext to track down the XML resources. Is this any better (from memory standpoint)?
Even better might be to declare the Resources object as public static in the main application and then use it elsewhere, since resources is all you need.