开发者

how to raise interface from application class?

friends,

i am running async task from application onCreate()

now i want to raise an interface on completion of this task and implement it in ACtivity B.

any one guide me how to achieve this?

my Interface

public interface IBanksLoader 
{
    public void OnBankLoadingComplete(boolean complete);
}

in applicat开发者_如何学Cion class

AsyncTask
{

any other function();
// to raise it here
}


Activity b
{

// implement it here to get result.
}

any help would be appreciated.


You can use the observer pattern to implement this behavior.

Activity B would implement the IBanksLoader (observer) interface and register itself to some central component. This central component must get notified when the AsyncTask finished and calls then OnBankLoadingComplete() (is equivalent to notify() of the Observer interface) of all registered observers.

I would suggest to use a Singleton or an Application class as central component as they can be accessed easily form anywhere within your application, also from the AsyncTask.

But be aware of your application's life cycle. So your might need to unregister Activity B at some time, e.g. before it gets destroyed. Otherwise the central component would call OnBankLoadingComplete() on an object which is null and thus raise a NullPointerException.

UPDATE

public class ActivityB extends Activity implements IBanksLoader {

    public void onCreate(){           
        ...

        MyApplication app = (MyApplication) getApplication();
        app.register(this);

        ...
    }

    public void OnBankLoadingComplete(boolean complete){

         // your code here ...
    }

    public void onDestroy(){
        MyApplication app = (MyApplication) getApplication();
        app.unregister(this);
    }
}


public class MyApplication extends Application{

    private List<IBanksLoader> observers = new ArrayList<IBanksLoader>();

    public void register(IBanksLoader observer){
        if(observer != null){
            oberservers.add(observer);
        }
    }

    public void unregister(IBanksLoader observer){
        if(observer != null){
            oberservers.remove(observer);
        }
    }

    public void taskfinished(){
        foreach(IBanksLoader bank : observers){
            if(bank != null){
                bank.OnBankLoadingComplete(true);
            }
        }
    }
}


public class MyTask extends AsyncTask{
    ... 

    public void onPostExecute(){
        MyApplication app = (MyApplication) getApplication();
        app.taskfinished();
    }
    ...    
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜