Search code examples
javaandroidandroid-broadcast

Local broadcast in android?


I have two activity activityA and activityB.

activityA is starting a background process and mean while it will also start activityB

background process started by activityA will finish after sometime. Is it possible to notify activityB when process is finish by activityA if activiyB in foreground and activotyA is background.


Solution

  • Yes it is definitely possible and LocalbroadcastMaanager is a good choice here is how you do it.

    In the long running process, write this at the end of the process

                LocalBroadcastManager.getInstance(context).sendBroadcast(
                    new Intent("backgroundProcessCallBack"));
    

    And in your activity you should have this (inside oncreate):

        LocalBroadcastManager.getInstance(context)
        .registerReceiver(mTaskListener, new IntentFilter("backgroundProcessCallBack"));
    

    where mTaskListener is a class level variable (BroadcastReceiver):

    private BroadcastReceiver mTaskListener = new BroadcastReceiver() {
    
        @Override
        public void onReceive(Context cxt, Intent intent) {
            // Do you stuff here. You got the callBack in your activity
        }
    };
    

    then unregister this receiver in activity's onDestroy() method.