skovmand skovmand - 1 month ago 11
Android Question

Can I use a callback method from a BroadcastReceiver?

Learning to use the BroadcastReceiver class in Android, I have written a small program to receive the battery charge state and write it to three TextView fields in an activity.

However, I have made the BroadcastReceiver as a separate class to make it more simple and separate from the activity. Therefore I have to find a method to tell my Activity class that the battery data has been updated, or, which is my solution, to pass in references to the TextView fields from the Activity to the BroadcastReceiver class.

Does anyone know whether it is possible to make a callback method from the BroadcastReceiver to start a function, f.ex. updateTextViews(); in the Activity?

Here is the source code - note there are two java files:
http://pastebin.com/qjCTsSuH

Regards, Niels.

Answer Source

I have made the BroadcastReceiver as a separate class to make it more simple

IMHO, you made it more complex.

Therefore I have to find a method to tell my Activity class that the battery data has been updated, or, which is my solution, to pass in references to the TextView fields from the Activity to the BroadcastReceiver class.

Option #1: Just go back to using an inner class for the BroadcastReceiver. ACTION_BATTERY_CHANGED can only be used via registerReceiver() anyway. Just have onReceive() call some method on the activity to do the work of updating the UI.

Option #2: Pass your activity into the constructor of the BroadcastReceiver, and call the method as in option #1.

Option #3: Use an event bus, like Square's Otto or greenrobot's EventBus.