Diffinitive规则使用Android的getBaseContext,getApplicationContext或使用活动的"这&Q​​UOT; [英] Diffinitive rules for using Android's getBaseContext, getApplicationContext or using an Activity's "this"

查看:154
本文介绍了Diffinitive规则使用Android的getBaseContext,getApplicationContext或使用活动的"这&Q​​UOT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我GOOGLE了这个问题了很多,已经发现,当使用许多不同的建议 getBaseContext getApplicationContext 或一个活动自身的指针。

I've googled this question a lot and have found many differing recommendations on when to use getBaseContext, getApplicationContext or an Activity's own this pointer.

三个规则,拿出频繁,似乎使很多的感觉是 -

Three rules that come up often and seem to make a lot of sense are -

  1. 对于长寿命参考一 关联活动 getApplicationContext 应使用 因为这存在,只要你的 应用程序存在
  2. 有关context的生命周期是 绑定到他们的活动,他们自己 活动背景下()应 使用
  3. 存储上下文指针静态 只有非常谨慎(如果 可能的话,一点都没有)
  1. For a long-lived reference to a context activity getApplicationContext should be used as this exists as long as your application exists
  2. For contexts whose life-cycles are bound to their activities, their own activity context (this) should be used
  3. Store context pointers statically only with great caution (and, if possible, not at all)

假设这是正确的,什么是使用 getBaseContext

Assuming these are correct, what is the use of getBaseContext?

我已经看到了在那里使用的是创造了新的意图了大量的例子 -

I've seen a great many examples where new intents are created using -

Intent intent = new Intent(getBaseContext(), myClass.class);

相对于 -

As opposed to -

Intent intent = new Intent(this, myClass.class);

这是正确的,或推荐,方法,为什么?

Which is the correct, or recommended, method and why?

推荐答案

在getBaseContext()是ContextWrapper的方法。而ContextWrapper是,代理功能实现语境,仅仅代表其所有调用另一个上下文。可以被子类修改行为,而不改变原有的语境。 (根据的javadoc)

The getBaseContext() is the method of ContextWrapper. And ContextWrapper is, "Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context." (as per javadocs)

因此​​,这是用于呼叫到另一个上下文委派

So this is used to delegate the calls to another context.

这篇关于Diffinitive规则使用Android的getBaseContext,getApplicationContext或使用活动的"这&Q​​UOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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