Search code examples
androidbroadcastreceivergoogle-cloud-messaging

Why my BroadcastReceiver is geting unregisted when my app runs in background?


I register a BroadcastReceiver in my activity to handle broadcast that it send by a GCMBaseIntentService when a message is arrived.When my app runs in foregound everything works fine but after a long time in backround even if I dont unregister receiver my activity dont work properly(dont receive the broadcast).How can I resolve that?

Becasuse it is my first time using BroadcastReceiver this is my code:

<receiver
     android:name="com.google.android.gcm.GCMBroadcastReceiver"
     android:permission="com.google.android.c2dm.permission.SEND" >
     <intent-filter>
         <action android:name="com.google.android.c2dm.intent.RECEIVE" />
         <category android:name="dim.taxigen.taxigen_driver"/>
     </intent-filter>
 </receiver>

In manifest.

registerReceiver(mreceiver, new IntentFilter(
             "dim.taxigen.taxigen_driver.DISPLAY_MESSAGE"));

and how i register in my Activity.


Solution

  • I assume you don't declare your BroadcastReceiver in your manifest but programmatically. That is most likely your problem, because if your app is in the background it may get killed at any moment when memory gets low. The longer it is in the background, the bigger is the chance that it gets killed.

    You can declare your BroadcastReceiver in xml like this:

    <receiver android:name="com.example.Receiver" >
            <intent-filter>
                ... // Put the broadcasts you want to receive here
            </intent-filter>
     </receiver>
    

    Just put that in the application tag in your manifest.