2

I have a extended broadcastreceiver class that listens for bluetooth connection/disconnection. I want it to change a color of some text in my GUIActivity. I don't have it as an inner class on purpose: to keep the GUI code more manageable/modular.

I know of one way to do this: register the receiver dynamically and pass it in the context of the activity. Then do the normal registering/unregistering in onResume and onPause. This solution can be seen at this post

However, I was hoping I could eliminate just a little bit more code by having my receiver registered in the manifest and not worry about registering/unregistering.

I have tried casting the context in the onReceive on the Broadcastreceiver as follows

((SmokinoGUI) context).indicateBTConnection();

This throws an exception saying that context cannot be cast to SmokinoGUI. indicateBTConnection() is a method in the SmoinoGUI activity that does what it says.

So, is there a way to call a method in an activity from a broadcastreceiver that has been registered in the manifest and has not been dynamically instantiated?

Robert
  • 91
  • 2
  • 7
  • indicateBTConnection() what this method do? Can u just put it in your BroadCastReceiver class? – bean_droid Aug 04 '15 at 03:27
  • It is located in the UI and from there I will do whatever seems reasonable to indicate a connection. Probably I will turn some "connected" text green for connection and "Disconnected" text red. I probably could do all of this from the receiver now that I know how to access the UI activity but it seems cleaner to have it as a function in the UI activity where it is easy to access all the required views – Robert Aug 04 '15 at 05:09

1 Answers1

1

So, is there a way to call a method in an activity from a broadcastreceiver that has been registered in the manifest and has not been dynamically instantiated?

There is lot of ways. My favorite is:

  1. Extends Application class and assign that class to your Application name attribute in Manifest.

  2. Add instance of your Activity in that class and create getter and setter to it, that you could reference to in Activity onCreate() .

  3. Get application in your BroadcasetReceiver and call the getter to the Activity.

If all this sound complicated, well, it really not, and it good logic to use in every app. I could add some code for example.

yshahak
  • 4,996
  • 1
  • 31
  • 37
  • It makes perfect sense. I have already extended the application class. I just never thought to store an instance of the activity there. I'll give that a try. – Robert Aug 04 '15 at 04:31
  • it worked for me as well. Perhaps the code could be more clear but it leaves the rest of the coding less cluttered -- ((SmokinoApp)context.getApplicationContext()).getSmokinoGUI().indicateBTConnection(); <-- eww – Robert Aug 04 '15 at 04:43
  • 1
    Better to check if Activity not null – yshahak Aug 04 '15 at 04:59