java getapplicationcontext_getContext()、getApplicationContext()、getBaseConte

大多数答案已经涵盖了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围起来。例如,如果需要检查“基本”上下文是否是Service, Activity或Application: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();

}

}}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值