Вопрос

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