Search code examples
androidandroid-intentandroid-activitybroadcastreceiver

Can a Broadcast Receiver send information to an Activity only if it is active without starting a new Activity?


I have a broadcast receiver that gets triggered on geofencing events and either "clocks in" or "clocks out" with the server. If my application's "Attendance" activity is already open I would like it to display the clocking status change but I don't want the Broadcast Receiver to start the activity if it's not open - in other words display the change "live" while the activity is open only.

The way I imagine doing this is with the Broadcast Receiver sending an Intent to the activity but name "startActivity()" doesn't sound encouraging unless there are any special flags I can pass to prevent starting an Activity that isn't already open - I can't seem to find any.

The other option would be to constantly poll the value while the activity is open but it doesn't seem optimal so I would only use it if there wasn't another way and I can't think of a reason why it couldn't be possible with Intents.


Solution

  • There are several different ways to accomplish the same task. One is registering a listener like the following example:

    MainActivity

    public class MainActivity extends AppCompatActivity
    {
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        
            Receiver.setOnReceiveListener(new Receiver.OnReceiveListener() {
                public void onReceive(Context Context, Intent intent)
                {
                    //Do something.
                }
            });
        }
    
        @Override
        protected void onDestroy()
        {
            super.onDestroy();
            Receiver.setOnReceiveListener(null);
        }
    }
    

    Receiver

    public class Receiver extends BroadcastReceiver
    {
        private static OnReceiveListener static_listener;
    
        public static abstract interface OnReceiveListener
        {
            public void onReceive(Context context, Intent intent);
        }
    
        public static void setOnReceiveListener(OnReceiveListener listener)
        {
            static_listener = listener;
        }
    
    
        @Override
        public final void onReceive(Context context, Intent intent)
        {
            if(static_listener != null) {
                static_listener.onReceive(context, intent);
            }
        }
    }