title: fragments, when am i "active"?
body: <p>i've been constantly frustrated by this and i can't find a good answer, so hoping someone here can offer guidance.</p>
  
  <p>i have a fragment that uses <code>AsyncTask</code> quite extensively. i'm constantly plagued by bugs where the fragment calls <code>getActivity()</code>, which returns null. i assume these are happening because some method in the fragment are invoked before the activity is attached, or after it is detached.</p>
  
  <p>what's the correct way to handle this in my code? i don't want to have this idiom littered all over the place,</p>
  
  <pre><code>Activity activity = getActivity();
  if (activity != null) { // do something }
  </code></pre>
  
  <p>looking at the docs for <code>Fragment</code>, i can come up with many possible hooks to solve this: <code>isDetached()</code>, <code>onActivityCreated()</code>, <code>onAttach()</code>, <code>isResumed()</code>, and so on. what is the right combination?</p>
  
  <p>EDIT:</p>
  
  <p>A few people have suggested canceling tasks when paused, but this implies that the standard idiom,</p>
  
  <pre><code>new AsyncTask&lt;...&gt;.execute();
  </code></pre>
  
  <p>cannot be used. It implies that every exec'd <code>AsyncTask</code> needs to be tracked to completion, or canceled. I have simply never seen that in example code from Google or elsewhere. Something like,</p>
  
  <pre><code>private final Set&lt;AsyncTask&lt;?&gt;&gt; tasks = new HashSet&lt;&gt;;
  ...
  AsyncTask&lt;?&gt; t = new AsyncTask&lt;...&gt;() {
    ...
    public void onPostExecute(...) {
      tasks.remove(this);
      ...
    } 
  }
  tasks.add(t);
  t.execute();
  ...
  @Override
  public void onPause() {
    for (AsyncTask&lt;?&gt; t: tasks) {
      t.cancel();
    }
    tasks.clear();
  }
  </code></pre>