将活动上下文传递到静态方法中,是否可能发生内存泄漏? [英] Passing a activity context into a static method, memory leak potential?

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

问题描述

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

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.

您要启动的活动实现了静态的launch(Context context)方法,该方法设置了意图,标志等,并最终启动了该活动.

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之外设置活动中的标志,但这似乎并没有足够的理由合理地将该活动的上下文传递给静态方法.

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天全站免登陆