Wednesday, January 23, 2013

Leaking Activities

Important safety tip.  If a method or constructor requires a Context, don't pass it an Activity.  It works, but it's too dangerous.  It's just too easy to leak the activity.  Better to do activity.getApplicationContext().

Corollary:  Follow this rule except when you can't.  :-)  It turns out that if the code that requires the Context reference needs to start an activity, you'll get an exception if it doesn't set the FLAG_ACTIVITY_NEW_TASK flag in the Intent:

java.lang.RuntimeException: Unable to start activity ... Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag.  Is this really what you want?