Communication between Class and Main Activity Android

1.5k Views Asked by At

I am new in Android so I hope you can excuse my ignorance

I made an activity to control some bluetooth devices with my telephone, now that everything is working I would like to generate a new class from this activity, a class to take care of all bluetooth communication.

I have some questions:

First: In my activty I employed one broadcast receiver to listen to some actions of the Bluetooth Adapter like STATE_ON, BOND_BONDED... Using this actions I update my views, I call some methods and so on.

So, it is possible to keep listening to this broadcast receiver inside my class and then send the changes to my main activity to update the views and so on?

Second: I really need to send information from my bluetooth class to my main activity, information that I read from my devices, information from the broadcast receiver... so, which is the best way to pass information between a class and the main activity?

Well, thanks a lot for your help :)

1

There are 1 best solutions below

2
On

The onReceive() method of your BroadcastReceiver is called from the main thread: "This method is always called within the main thread of its process" (http://developer.android.com/reference/android/content/BroadcastReceiver.html#onReceive(android.content.Context, android.content.Intent)).

That means you can update your ui from the onReceive() method. All you need to do is use a local class like so:

BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // update the ui
    }
};

Register this receiver programmatically (instead of defining it in the manifest) and you're good to go:

Context.registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter)