1

Once you return from onReceive(), the BroadcastReceiver is no longer active, and its hosting process is only as important as any other application components that are running in it. This is especially important because if that process was only hosting the BroadcastReceiver (a common case for applications that the user has never or not recently interacted with), then upon returning from onReceive() the system will consider its process to be empty and aggressively kill it so that resources are available for other more important processes.

This means that for longer-running operations you will often use a Service in conjunction with a BroadcastReceiver to keep the containing process active for the entire time of your operation.

The above text has been taken from android site. But I am unable to find how to use a Service in conjunction with a BroadcastReceiver. Can someone please share some link for this or any example?

I found this link - stackoverflow. Is this the correct way of doing it?

Community
  • 1
  • 1
Popeye
  • 1,548
  • 3
  • 25
  • 39

1 Answers1

1

The BroadcastReceiver is one way you can set up communication between your service and your application/activity. Basically the service can send a broadcast to your activity, then your activity will handle whatever it needs to inside the onReceive().

Inside your service you would send a broadcast using an intent with a specific intent action, in your activity you would register a receiver with the same action. This way when you send a broadcast your activity will be able to receive it.

A good example / place to start: (Look at section 7 for full code example) http://www.vogella.com/articles/AndroidServices/article.html

Good Luck!

DejanRistic
  • 2,039
  • 18
  • 13
  • But that would mean that the Activity would have to be started in order to receive the Broadcast. What if I don't want to display an Activity, but instead receive the Broadcast in a background thread to display a notification to the user? – IgorGanapolsky Feb 05 '15 at 13:50
  • 1
    You don't need to start an activity, you can setup a local notification in the receiver without ever touching or starting an activity. You can register a receiver in your manifest or from your application class. As of 3.1 I believe the app will have to be started at least once to listen to registered broadcasts in the manifest. Its very common to intercept remote notifications (like Parse or SNS) and handle them using a receiver without actually starting an activity by registering it in the manifest. – DejanRistic May 24 '16 at 17:09