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
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).