活动和语境的区别是什么?

活动和上下文是相同的,还是有区别?

我应该在什么时候让一个方法传递一个活动,什么时候传递一个上下文?

46561 次浏览

As far as I understand: Context is the Base Object. So every Activity same as Application derives from Context. This means that every Activity and every Application IS a Context;

From developer.android.com Activity

java.lang.Object
↳ android.content.Context
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity

And Application

java.lang.Object
↳   android.content.Context
↳    android.content.ContextWrapper
↳    android.app.Application

An Application context lasts, as long as your app is alive, while the Activity context dies with your Activity (it is not valid after onDestroy of that Activity).

So if you need the Context across Activities (i.e. in a Singleton) you will be better off using an Application context.

Usually on Android Framework methods where a context is expected, it makes no difference which one you pass. But be always aware of MemoryLeaks if you're keeping long-living References to a Context

As You can see on the Android doc:

The Activity class extends from "ContextThemeWrapper", and this one from "ContextWrapper", and that one from "Context".

So, yes, An Activity extends the Context!