2

Is it possible that BroadcastReceiver in an activity which have gone to background receiving broadcast? If not, what should I do?

EDIT:

Let me clarify what I really need. I have a service that will receive data from bluetooth. When it get data from blue-tooth device successfully, the service will broadcast.

And there are three cases of the activity.

  1. foreground

Popup a dialog and ask for user something I think it can be simply done by register receiver in activity

  1. background

I just don't know how to do this part. If I register the receiver in application, notification is shown. After taking a look of the answers below, I think I can register in Application.

  1. sleep Wake up the device.

Thank You.

Bear
  • 5,138
  • 5
  • 50
  • 80

3 Answers3

5

You probably don't even want that. Activities are not designed to be used that way.

You should use a service to handle it. Or start an Activity if it needs to have an UI.

There two alternatives the way I see it.

  1. Have a service running and register the receiver there instead.
  2. If possible you can register the broadcast receiver in the manifest instead and handle it there. Please keep in mind that the receiver will run on the main thread, so you should signal to a running service or start a service or activity here. Perhaps a service that performs a single task.

A service that performs a single task can easily be implemented using IntentService. It is kind of like an async task wrapped in a service.

Sebastian Olsson
  • 836
  • 6
  • 10
  • As an addition to point two I would like to add that the service will also run on the main thread unless you handle threading there or get it for free with IntentService – Sebastian Olsson Feb 17 '12 at 17:42
3

Is it possible that BroadcastReceiver in an activity which have gone to background receiving broadcast? If not, what should I do?

It is possible that you will receive notification anytime after when you call registerReceiver and before you call unregisterReceiver. If you are receive broadcasts when you are in the "background" it probably means you didn't tie the register and unregister calls to the appropriate methods in your Activity's lifecycle.

Nick Campion
  • 10,479
  • 3
  • 44
  • 58
3

If you register the broadcast receiver with the activit's context, it will receive broadcasts as long as the activity is alive.

however, you can register the receiver with the applicatino context, and it will still receive broadcasts even if the activity isn't alive.

dor506
  • 5,246
  • 9
  • 44
  • 79
  • 1
    But this clutters the application with a matter that should be private to the activity or some separate handler. The fact that the activity must be alive is a big 'if' as well. – Sebastian Olsson Feb 17 '12 at 17:41