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.

有帮助吗?

解决方案

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.

其他提示

You cannot have two activities running at the same time. If your background process runs in a Service, you can subsribe to broadcasts in Activity A and in Activity B. When the work in Service is finished, it sends broadcast - and whatever Activity (A or B) is in foreground - it will receive a Broadcast.

Sample code here: Programmatically register a broadcast receiver

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top