getContext()、getApplicationContext()、getBaseConte

getContext()、getApplicationContext()、getBaseContext()和“this”之间的区别

.之间的区别是什么?getContext() , getApplicationContext() , getBaseContext(),和“this"?

虽然这是一个简单的问题,但我无法理解它们之间的基本区别。如果可能的话,请给出一些简单的例子。


缥缈止盈
浏览 2880回答 3
3回答

慕侠2389804

View.getContext():返回视图当前运行的上下文。通常是当前活跃的活动。Activity.getApplicationContext():返回整个应用程序的上下文(所有活动都在其内部运行的进程)。如果您需要一个与整个应用程序的生命周期相关联的上下文,而不仅仅是当前的活动,请使用它而不是当前的活动上下文。ContextWrapper.getBaseContext()如果需要从另一个上下文中访问上下文,则使用ContextWrapper。从ContextWrapper内部引用的上下文通过getBaseContext()访问。

守着一只汪

大多数答案已经涵盖了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();     }   }}

慕容森

getApplicationContext()-返回在应用程序中运行的所有活动的上下文。getBaseContext()-如果要从应用程序中的另一个上下文访问上下文,则可以访问。getContext()-只返回当前正在运行的活动的上下文视图。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android
Java