I need to check for net connectivity in my application. Nothing should work if there is no internet connectivity. This I have implemented using BroadcastReceivers, but I want the receivers to be unregistered (i.e. not getting called) when my application is in background. The receiver should only work when the user is using the app.
Initially, I had a broadcast Receiver registered in my manifest, but I noticed it got fired even when my app was in background. So, I chucked the idea.
Then, I registered the receiver in onResume(), and unregistered in onPause(). But, the problem with this is that if I go from activity A to activity B of my application, then receiver is unregistered on onPause() of A and again registered in onResume() of B. This makes the activity transition heavy. Even though, in such a case the unregister and register process shouldn't happen.
I only want the receiver to get unregistered when the user stops using the app, not during activity transitions, but it should also not keep running when app is in background. I thought of using services, but I want to detect change in net connectivity, which is done best with receivers.
So, is there a way to detect when the app goes in background so that I can unregister my receiver? If not, what is the best way to achieve my requirement?
I have code for registering, unregistering receivers and also for detecting connectivity changes already.