Reputation: 1358
I originally registered my broadcast receiver in my main Activity via code. However, I have IntentServices (that run in the background) which broadcast intents and as such, need the Broadcast Receivers to always be available. My method of registering the receivers in my code worked ok until the back button was pressed. Then, the receivers would be deregistered as the main activity would be destroyed.
As such, I had the idea to move the declaration of the receivers to the Manifest file. However, I am coming across a strange problem where everytime my code broadcasts an intent, a new instance of the broadcast receiver is created. What I want, is for a single instance of a broadcast receiver to be available at all times. This is due to the fact that my broadcast receiver creates and starts a timer, however if multiple instances of the receivers are created, then multiple timers are created which is not good.
Note: A single instance of my broadcast receiver can handle the case where it receives an intent but the timer is already started.
Here is my code in the Manifest file:
<receiver android:name=".StartTimerBroadcastReceiver" android:enabled="true" >
<intent-filter>
<action android:name="START_TIMER" />
</intent-filter>
</receiver>
And here is my code that broadcast intents:
Intent broadcastIntent = new Intent("START_TIMER");
broadcastIntent.putExtra("timerID", "timer1");
sendBroadcast(broadcastIntent);
Am I doing something wrong? Any help is appreciated. Thanks
Upvotes: 0
Views: 1781
Reputation: 7849
Its not possible to have one instance of BroadcastReceiver through Manifest.
What you can do is create a Static variable for your Timer.
If that is not the solution for your problem then create a Service and when a broadcast is received start the Service with some EXTRA in Intent specifying how to start the Time.(i.e just redirect the broadcast to your service).
Upvotes: 1
Reputation: 688
This is the way that BroadcastReceivers work. Check out http://developer.android.com/reference/android/content/BroadcastReceiver.html specifically the section titled "Receiver Lifecycle":
"A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.
This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes."
From what I have seen, this seems worse when registering a BroadcastReceiver in the manifest.
Upvotes: 1