Correct pattern for registering a receiver?
<p>I need to register a receiver. I have been using the following pattern:</p>

<pre><code>@Override
protected void onResume() {
    super.onResume();
    registerReceiver(myReceiver, new IntentFilter(...));
}

@Override 
protected void onPause() {
    super.onPause();
    unregisterReceiver(myReceiver);
}

private BroadcastReceiver myReceiver = new BroadcastReceiver() {
    ...
});
</code></pre>

<p>I'm getting crash reports from marketplace about my unregisterReceiver() call:</p>

<pre><code>java.lang.IllegalArgumentException: Receiver not registered
</code></pre>

<p>I thought this could not be possible, but it seems this is the correct pattern instead:</p>

<pre><code>private Intent mIntent;

@Override
protected void onResume() {
    super.onResume();
    if (mIntent == null) {
        mIntent = registerReceiver(myReceiver, new IntentFilter(...));
    }
}

@Override 
protected void onPause() {
    super.onPause();
    if (mIntent != null) {
        unregisterReceiver(myReceiver);
        mIntent = null;
    }
}

private BroadcastReceiver myReceiver = new BroadcastReceiver() {
    ...
});
</code></pre>

<p>Is the above the correct pattern? I guess it's possible for registration to fail, and we have to keep the result from registerReceiver(), and check it in onPause() before making the call to unregister()?</p>

<p>Thanks</p>

<hr>

<p>I am basing the change off of this question:
<a href="http://stackoverflow.com/questions/5036451/problem-with-broadcastreceiver-receiver-not-registered-error">Problem with BroadcastReceiver (Receiver not registered error)</a></p>

<p>I've only ever seen the first pattern above, never one where you check the intent response - any clarification would be great.</p>
