Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

android - What is the difference between Activity and Context?

Are Activity and Context the same, or are there differences?

When should I have a method pass an Activity, and when a Context?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...