title: Android after handler removeCallbacksAndMessages still posting runnable in background thread
body: <p>I encountered an unusual NPE exception in Android with handler and background thread.</p>
  
  <p>I know when the activiy or fragment on destroy, the ui widget will be destroied, so you must cancel all the pending message or runnable sent from the background.</p>
  
  <p>For example, in the fragment callback <code>onDestroyView</code>, i call handler' s <code>removeCallbacksAndMessages(null)</code> to remove all the callbacks. But, in some case, the callback still got executed, but at that time the ui has been destroied, the NPE throws.</p>
  
  <p>Below is the sample:</p>
  
  <pre><code>public class SampleFragment extends Fragment {
    private Handler mHandler = new Handler() {
      @Override public void handleMessage(Message msg) {
        switch (msg.what) {
          // do your job
        }
      }
    };
  
    @Nullable @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      // create some ui
      return super.onCreateView(inflater, container, savedInstanceState);
    }
  
    @Override public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
      new Thread(new Runnable() {
        @Override public void run() {
          // after a long running work
          mHandler.post(new Runnable() {
            @Override public void run() {
              // OOPS, the ui widget may null!
            }
          });
        }
      }).start();
    }
  
    @Override public void onDestroyView() {
      mHandler.removeCallbacksAndMessages(null);
      super.onDestroyView();
    }
  }
  </code></pre>
  
  <p>I notice at some point, in the <code>onDestroyView</code>, the handler has been remove all the pendding message or runnable which will attach to the ui thread, and the the view set to be null to be gc. But the thread may still in the running state, and the handler will post the runnable, but the view is null.</p>
  
  <p>The simple way is to check null from fragment' s <code>getView()</code> in the runnable, but if all of this situation needs to check null, that would be tedious.
  Is there any nice approach to slove this kind of problem?</p>
  
  <p>Thx in advance.</p>