Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is registering IabBroadcastReceiver in Activity a bad idea?

Tags:

android

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

like image 601
Sound Conception Avatar asked Nov 22 '15 05:11

Sound Conception


3 Answers

My guess is that the BroadcastReceiver may get destroyed if it's in an Activity. BroadcastReceivers 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.

like image 188
Andrew Orobator Avatar answered Nov 19 '22 01:11

Andrew Orobator


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

like image 28
Bhavdip Sagar Avatar answered Nov 19 '22 00:11

Bhavdip Sagar


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.

like image 2
vollen Avatar answered Nov 19 '22 02:11

vollen