将活动上下文传递给静态方法,内存泄漏的可能性? [英] Passing a activity context into a static method, memory leak potential?

查看:38
本文介绍了将活动上下文传递给静态方法,内存泄漏的可能性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了这种用于启动活动的特殊技术,在我看来,由于静态上下文,这似乎是一个坏主意,但我希望有人可能有这种方法背后的正当理由.

I've seen this particular technique for launching activities and it seems to me like a bad idea because of static contexts but I was hoping someone might have a legit reason behind this approach.

您要启动的 Activity 实现了一个静态启动(上下文上下文)方法,该方法设置了意图、标志等,并最终启动了该 Activity.

The activity you want to launch implements a static launch(Context context) method that sets up the intent, flags, etc and finally starts the activity.

public static void launch(Context context){
   Intent i = new Intent(context, SomeOtherActivity.class);
   // flag stuff
   context.startActivity(i);
}

然后一个 DifferentActivity 可以用一行代码去启动 SomeOtherActivity.

Then a DifferentActivity could go and launch SomeOtherActivity with one line.

SomeOtherActivity.launch(DifferentActivity.this);

我喜欢它如何允许您在远离启动它的 DifferentActivity 的情况下设置 Activity 中的标志,但这似乎不足以合理地将该 Activity 的上下文传递给静态方法.

I like how it allows you to setup the flags in the activity away from the DifferentActivity that is launching it but it doesnt seem like a good enough reason to rationalize passing that activity's context into a static method.

这不会导致 DifferentActivity 不被垃圾收集,因为现在静态方法有对它的引用吗?这对我来说似乎是内存泄漏,并且可能不是一个好主意,只是为了能够保留正在创建的活动中包含的标志.

Wouldn't this cause DifferentActivity to not be garbage collected because now that static method has a reference to it? This seems like a memory leak to me and probably not a good idea to do just to be able to keep the flags contained in the activity that is being created.

我在这里遗漏了什么使这是一个很好的做法吗?

Is there something I'm missing here that makes this a good practice to do?

推荐答案

将某些内容传递给静态函数并不是潜在的内存泄漏.将变量存储在静态变量中是.这种技术是完全安全的.我什至推荐使用它,因为您可以将变量传递给函数并将它们存储在将要使用这些附加项的类中的附加项中,从而减少需要知道它们存在以及它们如何存在的地方的数量布置

Passing something into a static function isn't a potential memory leak. Storing a variable in a static variable is. This technique is perfectly safe. Its one I'd even recommend, as you can pass in variables to the function and store them in extras inside the class that is going to use those extras, reducing the number of places that need to know of their existence and how they're laid out

这篇关于将活动上下文传递给静态方法,内存泄漏的可能性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆