首页 > 解决方案 > Android - Why people refer to a static context inline repeatedly, instead of pass it in the Method() once?

问题描述

I'm approaching completion of my first true App..
Along my road (in the past couple years) I've seen many examples of code.
One thing is consistent: I always see the use of static context references such as:
getApplicationContext(), this.getActivity(), and many other such references..

But earlier today, after asking how to retrieve Context from a Method within a Receiver,
I was told simply "pass it the Context", ex: public void receiverMethodCall(Context context).

My Question is: If it's that simple, why do people frequently make repeated static context references inline within their code, over and over again, instead of simply passing the containing Method a Context to begin with, and referring to it using "context" when needed?

标签: javaandroidandroid-activitybroadcastreceiverandroid-context

解决方案


我希望我明白了你的问题的含义——你得到了答案并被告知将上下文作为上下文类型变量传递——但不要忘记,当你想调用你的方法并传递一个上下文时,你必须知道什么这个上下文是并初始化它。

例如,如果你想制作一个 Toast 方法参数之一是上下文,如果你使用很多 Toast,最好有上下文引用并在每次你想显示 Toast 时使用它(或使用任何其他需要上下文的方法。)而不是使用this.getActivity()or getApplicationContext()
通过这样做,您可以防止重复代码,并且您不需要在代码中多次引用上下文,现在关于“为什么人们经常在他们的代码中内联重复静态上下文引用”

我可以想到一种情况,即进行 2 个上下文引用并不是一件坏事:假设您在同一个活动中有 2 个方法正在使用上下文 - 如果这些方法被使用一次,那么您可以在内部创建上下文引用该方法并让垃圾收集器处理该引用。

我不得不说我同意你的观点,我认为如果它的可选只是将上下文传递给你的方法并让它使用它,那么它真的很简单。


推荐阅读