I have a broadcast receiver which is being triggered the moment it\'s registered (and subsequently retriggered with onPause / onResume), surely this is the wrong behaviour?
Here's another solution that worked for me:
class FooActivity extends Activity {
private Intent mReceiverRegisteringIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
broadcastReceiver = new FooBroadcastReceiver();
intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
}
@Override
protected void onResume() {
super.onResume();
mReceiverRegisteringIntent = registerReceiver(connectivityReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(connectivityReceiver);
}
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (connectivityAction(intent)) {
Log.d("footag", "onReceive");
//if mReceiverRegisteringIntent is not null, then this is the sticky
//broadcast received when registering the receiver for the first time
if (mReceiverRegisteringIntent != null) {
//set it to null for future broadcasts
mReceiverRegisteringIntent = null;
return; //do nothing
}
//logic for future broadcasts
...
}
}
private boolean connectivityAction(Intent intent) {
return ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction());
}
}
}
I'm assuming that MyBroadcastReceiver
is an inner class for FooActivity
so it can access mReceiverRegisteringIntent