What is faster Communicating, sending broadcast VS calling activity method directly in Android?

communication between two fragments using interface
communicate between activity and fragment
fragment to fragment communication without activity
establishing communication between a service and activity android
android callback from activity to fragment
service to activity communication android
implement interface in fragment android
call fragment method from activity using interface

In my app, I have to call an activity method from the fragment.

I know I can do this in two ways:

1. Via sending a broadcast to activity:

Intent intent = new Intent("FILTER"); intent.putExtra("EXTRA", 1); sendBroadcast(intent);

2. Or Calling the activity method directly:

((MyActivity) getActivity()).method();

I would like to know which way is faster and safe to communicate. Any help would be appreciated.

Thank you.

Loosely Coupled Fragment?

I am not sure about the speed. But on the design perspective You should use an interface to communicate with an Activity rather calling Activity method directly from your Fragment. ie ((MyActivity) getActivity()).method();

Because using an interface makes your Fragment independent from your Activity. Let's say in future you want to use your fragment in Some other Activity then you will not have to change anything in your Fragment.

Interface

public interface Somelistener {

     public void someMethod();

}

Your Loosely coupled Fragment

YourFragment extends Fragment {

   Somelistener listener;

    public void onActivityCreated(Context context){

      listener = (SomeLisner)context;

    }

    public void buttonClick()
    {
       listener.someMethod();
    }

}

So if you are using in your MainActivity. No problem

MainActivity implements SomeListener{

   @Override
   public void someMethod()
   {
      // Activity method
   }
}

In future you want to use Fragment in SomeOtherActivity. No problem

SomeOtherActivity implements SomeListener{

   @Override
   public void someMethod()
   {
      // somethother method
   }
}

BroadcastReceiver Approach? TBH I have seen this approach for Service-Activity Communication. Not for Activity - Fragment communication.

Dynamic Broadcast Receiver in Fragment, What is faster Communicating, sending broadcast VS calling activity method directly in Android? In my app, I have to call an activity method from the fragment. The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment's public methods. For instance, imagine that the activity shown above may contain another fragment that's used to display the item specified by the data returned in the above callback method.

For communicating between Fragments and the Activity that contains it, there's actually a much better 3rd option.

The better option is to use an Interface as a callback method. This is described very well in this documentation: https://developer.android.com/training/basics/fragments/communicating

Using an interface is much more preferred over your two methods because it's both safer and more efficient.

For your first method of using Broadcast Receivers, this is actually a very inefficient solution due to Broadcast Receivers not being meant for a task like what you're after.

Let me quote you something from the Android documentation:

Warning: Limit how many broadcast receivers you set in your app. Having too many broadcast receivers can affect your app's performance and the battery life of users' devices. For more information about APIs you can use instead of the BroadcastReceiver class for scheduling background work, see Background Optimizations. https://developer.android.com/guide/topics/manifest/receiver-element

So yes, Broadcast Receivers will have a bigger effect on your app's performance and the device's battery life over the other method you suggested and the method I suggested.

Additionally, don't forget that a Broadcast Receiver is meant to listen to broadcasts. The type of Broadcast Receiver you're using in your example is actually a Global Broadcast where you didn't explicitly limit it's "range", so any Broadcast Receiver could potentially "listen" in to your broadcast. In terms of security, using a Global Broadcast like this isn't safe either.

You also don't want other apps to potentially fire off a Broadcast that coincidentally coincides with your app's Broadcast Receiver, causing it to receive data not meant for it and crashing due to this accidental and coincidental naming.

Honestly, there's more potential issues of using a Broadcast Receiver in a way it's not meant for.

As for your second method of directly calling the Activity's method... this is actually very inefficient for managing code. You're basically tying the Fragment tightly together with that specific Activity.

However, Fragments, by design, makes it common to be swapped into other Activities or Fragments... you'll basically have to do multiple if statements and casts each time you want to run code from it's parent.

Also, keep in mind that if you later change code in MyActivity, it can cause problems for this fragment due to you forgetting how tightly bound it is to the Activity.

But if you use the more preferred Callback Interface approach, it's simply a middleman meant to deliver a "Hey, DO something for me" message. Quick and direct. It's also plays friendly with any Activity or Fragment you want to attach this Fragment to later since those Activities or Fragments simply have to implement the Interface and the callback bridge between both parent and child is formed.

Communicate with other fragments, Two Fragments should never communicate directly. the activity by calling the onArticleSelected() method (or other methods in the interface)  As a user navigates through, out of, and back to your app, the Activity instances in your app transition through different states in their lifecycle. The Activity class provides a number of callbacks that allow the activity to know that a state has changed: that the system is creating, stopping, or resuming an activity, or destroying the process in which the activity resides.

It is better to use interface to communicate from fragment to activity rather than a Local broadcast. Activity will implement the interface and fragment will call the methods.

Application Fundamentals, Each component is an entry point through which the system or a user can enter your app. For example, an email app might have one activity that shows a list of Music playback is something the user is directly aware of, so the app You can initiate a broadcast by passing an Intent to methods such as  You can use broadcasts and registered receivers for the communication. For example, your activity can register a broadcast receiver for an event and the service sends outs corresponding events. This is a very typical scenario, in which the service need to signal to the activity that his processing has finished.

Introduction to Activities, This state occurs when, for example, the user taps the Back or Recents button. When the system calls onPause() for your activity, it technically  For the class' constructor, you most likely want to have parameters for the WifiP2pManager, WifiP2pManager.Channel, and the activity that this broadcast receiver will be registered in. This allows the broadcast receiver to send updates to the activity as well as have access to the Wi-Fi hardware and a communication channel if needed.

Intents and Intent Filters, Although intents facilitate communication between components in several ways, there If you want to receive a result from the activity when it finishes, call you can start a service by using methods of the Service class. You can deliver a broadcast to other apps by passing an Intent to sendBroadcast() or  An Activity is an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface…

Different Ways of Communicating between Activity and Service, This instance then can be used to call public functions of the service. public class directly access it. If you want to send broadcasts to your application components only then use You can use EventBus from greenrobot or otto from square. If there are some other better suggestions please comment. Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself.These messages are sometime called events or intents. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this

Comments
  • You can use a listener (Interface) as well to communicate back to Activity. And I have never seen anyone using a BroadcastReceiver to bridge a Fragment and Activity Communication.
  • Use interface, it will be better, activity will implement the interface, and fragment will call the method using listener
  • why don't you log the time in logcat and see yourself which is faster?
  • I'm against the second method because it means the fragment can't live without the specific MyActivity class. It also assumes the activity it's attached to is always of type MyActivity.