In Google's in-app billing Trivial Drive sample, a BroadcastReceiver
is registered to listen for messages about updated purchases, after the IabHelper setup has successfully completed.
The author however has included the following note:
Note: registering this listener in an Activity is a bad idea, but is done here because this is a SAMPLE.
Why is this a bad idea for this listener?
This comment can be found in the OnIabSetupFinishedListener
definition in the onCreate
method of MainActivity
in the source code for the Trivial Drive sample
My guess is that the BroadcastReceiver
may get destroyed if it's in an Activity
. BroadcastReceiver
s are usually declared in the manifest and are not manually instantiated by the developer, but by the OS. If it is registered in code, the only reference the Android OS has to the BroadcastReceiver
is that particular instance which is tied to the lifecycle of the Activity
it's contained in. If that Activity
were to die/finish/stopped to save memory, then the BroadcastReceiver
declared inside would most likely stop receiving updates.
As we know the broadcast receiver should not bounded with activity it should separate from activity lifecycle. Usually the broadcast receiver should define inside the androidmanifest file. Doing this allow activity can easy listen the update when it clearly visible to the user and avoid listen in case activity no long visible to the user by un register inside onStop/onDestroy.
The best way to implement it using Eventbus + Broadcast receiver class. Define the receiver into the android manifest. when the update come it will inform to the receiver class. We fire the event that will send to each activity that register event would receive this message. This way inside your application where you need the update you can easily subscribe and listen the event. Thanks
Because if we register a BroadcastReceiver in Activity, then it's lifecycle is bind to the Activity's lifecycle. So when the Activity is destory, the Receiver will not worked. Therefore it can not receive any boardcasts while the Activity is not running.
May be you will lose the boardcast which of user's purchase.
In this sample, we always call mHelper.queryInventoryAsync(mGotInventoryListener);
in the Activity's OnCreate() function. So we don't worry about that as the author comment in the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With