For the More Curious: The Application Context

Earlier in this chapter, you used the application context in the constructor of the CrimeLab.

private CrimeLab(Context context) {
  mContext = context.getApplicationContext();
  ...
}

What makes the application context special? When should you use the application context over an activity as a context?

It is important to think about the lifetime of each of these objects. If any of your activities exist, Android will have also created an application object. Activities come and go as the user navigates through your application, but the application object will still exist. It has a much longer lifetime than any one activity.

The CrimeLab is a singleton, which means that once it is created, it will not be destroyed until your entire application process is destroyed. Also, the CrimeLab maintains a reference to its mContext object. If you store an activity as the mContext object, that activity will never be cleaned up by the garbage collector because the CrimeLab has a reference to it. Even if the user has navigated away from that activity, it will never be cleaned up.

To avoid this wasteful situation, you use the application context so that your activities can come and go and the CrimeLab can maintain a reference to a Context object. Always think about the lifetime of your activities as you keep a reference to them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.235.130.73