0

I want to figure out whether the Context object of one activity is being leaked to another activity. Does the following code leak the context of one activity to another?

Intent intent = new Intent(context, Demo.class);
context.startActivity(intent);
Harshal Kshatriya
  • 5,630
  • 11
  • 44
  • 60
  • 1
    [Check this one](http://stackoverflow.com/questions/9227835/use-of-context-to-start-another-activity/9227958#9227958) – Lalit Poptani May 01 '12 at 06:40

2 Answers2

2

No, that doesn't "leak" your context. In general, to avoid leaking an Activity context, here's a few tips to follow:

  • Never hold a static reference to a Context
  • Do not pass Views between Activitys
  • Whenever you don't need a Context with an Activity reference, use the application's Context (context.getApplicationContext()).
  • Use WeakReference when holding onto a Context while running some background operation (or whenever feasible really)
Jason Robinson
  • 31,005
  • 19
  • 77
  • 131
  • I have a question about bullet point 3 - why not always use an Application Context do avoid doubt? – barry May 04 '12 at 06:24
  • @barry There are some things that should be tied to the lifecycle of an `Activity`, such as registering a `BroadcastReceiver` or starting a new `Activity`. The later requires an `Activity` `Context` so the new `Activity` has a task to start in (Otherwise you'd need to use the `FLAG_ACTIVITY_NEW_TASK` flag). – Jason Robinson May 04 '12 at 15:40
0

As an addendum, use the Memory Analysis Tool (MAT) for eclipse to inspect a heap dump.

Bondax
  • 3,143
  • 28
  • 35