使用 Android 的 getBaseContext、getApplicationContext 或使用 Activity 的“this"的区别规则 [英] Diffinitive rules for using Android's getBaseContext, getApplicationContext or using an Activity's "this"

查看:22
本文介绍了使用 Android 的 getBaseContext、getApplicationContext 或使用 Activity 的“this"的区别规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在谷歌上搜索了很多这个问题,并发现了许多关于何时使用 getBaseContextgetApplicationContext 或 Activity 自己的 this 的不同建议指针.

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. 对于生命周期为绑定到他们的活动,他们自己的活动上下文(this)应该是使用
  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?

我见过很多使用 -

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

相对于 -

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

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

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

推荐答案

getBaseContext() 是 ContextWrapper 的方法.而 ContextWrapper 是,代理 Context 的实现,它只是将其所有调用委托给另一个 Context.可以在不改变原始 Context 的情况下进行子类化以修改行为."(根据javadocs)

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.

这篇关于使用 Android 的 getBaseContext、getApplicationContext 或使用 Activity 的“this"的区别规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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