关闭

Android getActivity(), getContext(), getApplication()和getApplicationContext()

标签: androidContextApplicatiothis
2243人阅读 评论(0) 收藏 举报
分类:
  1. getActivity():
    This method gives the context of the Activity. You can use it is like the yourActivity.this. The method getActivity() is normally used in fragments to get the context of the activity in which they are inserted or inflated.

  2. getContext():
    Returns the context the view is currently running in. Usually the currently active Activity. getContext() is not defined in an Activity. It’s used in a View (or View subclass) to get a reference to the enclosing context (an Activity).

Activity is a subclass of Context.

When you call getActivity() you get an Activity which is a Context as well. But when you call getContext you will get a Context which might not be an Activity.

When using newer version of Support Library, when Fragment is not hosted by an Activity you can get different objects when calling getActivity() and getContext().

3.getApplication():
getApplication() is available to Activity and Services only. Although in current Android Activity and Service implementations, getApplication() and getApplicationContext() return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation). So if you want the Application class you registered in the Manifest, you should never call getApplicationContext() and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).

4.getApplicationContext():
Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.

What’s the difference between the various methods to get a Context?

 public class MyActivity extends Activity {
    public void method() {
       mContext = this;    // since Activity extends Context
       mContext = getApplicationContext();
       mContext = getBaseContext();
    }
 }

http://stackoverflow.com/questions/1026973/whats-the-difference-between-the-various-methods-to-get-a-context

0
1

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:53912次
    • 积分:1163
    • 等级:
    • 排名:千里之外
    • 原创:64篇
    • 转载:2篇
    • 译文:0篇
    • 评论:9条
    文章分类
    最新评论