3 回答

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

TA贡献1872条经验 获得超3个赞
getContext()
getApplicationContext()
getBaseContext()
ContextWrapper
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
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(); } }}

TA贡献1853条经验 获得超18个赞
getApplicationContext()
getBaseContext()
getContext()
添加回答
举报