我的活动正在尝试创建一个AlertDialog,它需要一个上下文作为参数。如果我使用:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
然而,我对使用“this”作为上下文持怀疑态度,因为即使在屏幕旋转这样简单的操作中,Activity被破坏和重新创建时,也有可能发生内存泄漏。来自Android开发者博客的相关文章:
There are two easy ways to avoid context-related memory leaks. The most obvious one is to avoid escaping the context outside of its own scope. The example above showed the case of a static reference but inner classes and their implicit reference to the outer class can be equally dangerous. The second solution is to use the Application context. This context will live as long as your application is alive and does not depend on the activities life cycle. If you plan on keeping long-lived objects that need a context, remember the application object. You can obtain it easily by calling Context.getApplicationContext() or Activity.getApplication().
但是对于AlertDialog(), getApplicationContext()或getApplication()都不能作为上下文,因为它会抛出异常:
"无法添加窗口-令牌null不是用于应用程序"
参考文献:1、2、3等。
所以,这真的应该被认为是一个“bug”,因为我们被正式建议使用Activity.getApplication(),但它并没有像宣传的那样发挥作用?
Jim
当你说“…”时,你已经正确地发现了问题。对于AlertDialog(), getApplicationContext()或getApplication()都不能作为上下文,因为它会抛出异常:'无法添加窗口-令牌null不是用于应用程序'"
要创建一个对话框,您需要一个活动上下文或服务上下文,而不是应用程序上下文(getApplicationContext()和getApplication()都返回一个应用程序上下文)。
下面是获取活动上下文的方法:
(1)在一项活动或服务中:
AlertDialog。生成器生成器=新的AlertDialog.Builder(这个);
(2)片段:
AlertDialog。生成器生成器= new AlertDialog.Builder(getActivity());
内存泄漏不是“this”引用固有的问题,它是对象对自身的引用(即引用用于存储对象数据的实际分配内存)。它发生在垃圾收集器(GC)在分配的内存超过其有效寿命后无法释放的任何已分配内存上。
Most of the time, when a variable goes out of scope, the memory will be reclaimed by the GC. However, memory leaks can occur when the reference to an object held by a variable, say "x", persists even after the object has outlived its useful lifespan. The allocated memory will hence be lost for as long as "x" holds a reference to it because GC will not free up the memory for as long as that memory is still being referenced. Sometimes, memory leaks are not apparent because of a chain of references to the allocated memory. In such a case, the GC will not free up the memory until all references to that memory have been removed.
为了防止内存泄漏,请检查代码中是否有逻辑错误导致已分配的内存被“this”(或其他引用)无限引用。还记得检查链引用。这里有一些工具可以帮助你分析内存使用,并找到那些讨厌的内存泄漏:
JRockit任务控制中心
JProbe
YourKit
AD4J
对我有用的是传递活动而不是上下文。
我想为我的对话框创建一个自定义布局,但为了保持我的代码独立,我在一个单独的类中创建了它,否则我将不得不复制并粘贴那块代码到我想使用对话框的每个活动中。
Solution解释了我的情况,但它给出了核心解决方案:
当我使用ViewAdapter时,我初始化了活动适配器(不是上下文ex. ->[kotlin]活动:活动)作为参数-> ex. [kotlin] this@MainActivity
然后我把这个参数传递给Viewholder
然后再次将它传递给将膨胀Dialog的类。
在任何地方使用activity[可选名称]:activity[强制类型],直到它到达你想要膨胀的对话框
它有很多传递,但它比复制和粘贴相同的代码在任何地方更有意义