1

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.

Ankit Aggarwal
  • 2,367
  • 24
  • 30
  • You say "This makes the activity transition heavy". Although registering and unregistering the receiver in each activity may appear excessive, my guess is that the processing is insignificant compared to everything else that happens on activity change. If you are bothered by the duplicated code in the `onResume()` and `onPause()` methods, you could put that in a base `Activity` class and derive your activities from that. – Bob Snyder Jul 05 '15 at 15:21
  • Yes, you are right, here is some other processing I do when I re-register the receiver, and that takes time. I check for net connectivity that time, but it is important. – Ankit Aggarwal Jul 05 '15 at 16:16
  • Detailed discussion of [the issue here](http://stackoverflow.com/questions/3667022/checking-if-an-android-application-is-running-in-the-background). Many answers using both API 14 capabilities and earlier. – Bob Snyder Jul 05 '15 at 16:31
  • Thanks for your help. This was exactly what I needed. Cheers :) – Ankit Aggarwal Jul 06 '15 at 17:03

0 Answers0