为了账号安全,请及时绑定邮箱和手机立即绑定

getContext()、getApplicationContext()、getBaseConte

getContext()、getApplicationContext()、getBaseConte

缥缈止盈 2019-06-18 15:50:38
getContext()、getApplicationContext()、getBaseContext()和“this”之间的区别.之间的区别是什么?getContext() , getApplicationContext() , getBaseContext(),和“this"?虽然这是一个简单的问题,但我无法理解它们之间的基本区别。如果可能的话,请给出一些简单的例子。
查看完整描述

3 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

  • View.getContext():返回视图当前运行的上下文。通常是当前活跃的活动。

  • Activity.getApplicationContext():返回整个应用程序的上下文(所有活动都在其内部运行的进程)。如果您需要一个与整个应用程序的生命周期相关联的上下文,而不仅仅是当前的活动,请使用它而不是当前的活动上下文。

  • ContextWrapper.getBaseContext()如果需要从另一个上下文中访问上下文,则使用ContextWrapper。从ContextWrapper内部引用的上下文通过getBaseContext()访问。


查看完整回答
反对 回复 2019-06-18
?
守着一只汪

TA贡献1872条经验 获得超3个赞

大多数答案已经涵盖了getContext()getApplicationContext()getBaseContext()很少被解释。

方法getBaseContext()只有当您有ContextWrapper..Android提供了一个ContextWrapper类,该类是围绕现有的Context使用:

ContextWrapper wrapper = new ContextWrapper(context);

使用ContextWrapper它允许您“在不更改原始上下文的情况下修改行为”。例如,如果您有一个名为myActivity然后可以创建一个View有着不同的主题myActivity:

ContextWrapper customTheme = new ContextWrapper(myActivity) {
  @Override
  public Resources.Theme getTheme() { 
    return someTheme;
  }}View myView = new MyView(customTheme);

ContextWrapper是非常强大的,因为它允许您覆盖Context包括访问资源的代码(例如:openFileInput()getString()),与其他组件(例如:sendBroadcast()registerReceiver()),请求权限(例如,checkCallingOrSelfPermission())和解析文件系统位置(例如,getFilesDir()). ContextWrapper对于解决特定于设备/版本的问题或对需要上下文的视图等组件应用一次性自定义非常有用。

方法getBaseContext()可用于访问ContextWrapper围起来。例如,如果需要检查“基本”上下文是否是ServiceActivityApplication:

public class CustomToast {
  public void makeText(Context context, int resId, int duration) {
    while (context instanceof ContextWrapper) {
      context = context.baseContext();
    }
    if (context instanceof Service)) {
      throw new RuntimeException("Cannot call this from a service");
    }
    ...
  }}

或者,如果您需要调用方法的“未包装”版本:

class MyCustomWrapper extends ContextWrapper {
  @Override
  public Drawable getWallpaper() {
    if (BuildInfo.DEBUG) {
      return mDebugBackground;
    } else {
      return getBaseContext().getWallpaper();
    }
  }}


查看完整回答
反对 回复 2019-06-18
?
慕容森

TA贡献1853条经验 获得超18个赞

getApplicationContext()-返回在应用程序中运行的所有活动的上下文。

getBaseContext()-如果要从应用程序中的另一个上下文访问上下文,则可以访问。

getContext()-只返回当前正在运行的活动的上下文视图。


查看完整回答
反对 回复 2019-06-18
  • 3 回答
  • 0 关注
  • 2879 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号