Google Code Prettify - 輕量級的語法上色工具

星期二, 8月 04, 2015

Context 的使用 (Activity Context, Application Context, getBaseContext.....)

In a regular Android application, you usually have two kinds of Context, Activity and Application.

1.Activity Context
this.getContext()= Activity.this 屬於Activity,Activity摧毀他就摧毀

  • View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.


2.Application Context
 getApplicationContext()
生命週期是整個app應用,app摧毀它才摧毀,
但是使用的時候要注意,和activity生命週期掛鉤的任務不要使用該context,比如網絡訪問,防止內存洩露

  • 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.


3.Don't use getBaseContext(), just use the Context you have.
getBaseContext()一般情况下不推荐使用这种方法


  • ContextWrapper.getBaseContext(): If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from inside that ContextWrapper is accessed via getBaseContext().

4.getActivity():在fragmentNotification中會使用到
Notification http://nkeegamedev.blogspot.tw/2010/06/android-notification.html
fragment http://developer.android.com/reference/android/app/Fragment.html

5.getParent() 

6.this