How to call a returning value function in AsyncTask

吃可爱长大的小学妹 提交于 2019-12-01 14:15:55

For myself i do this with a callback Function, that i invoke after onPostExecute.

public AsyncUnzip(Activity ctx, Observer callback) {
    this.ctx = ctx;
    this.callback = callback;
}

and

@Override
protected void onPreExecute() {
    super.onPreExecute();
    dia = new ProgressDialog(ctx);
    dia.setTitle("Bitte warten");
    dia.setMessage("Geodatenpaket wird entpackt...");
    dia.setCancelable(false);
    dia.show();
}

and

@Override
public void onPostExecute( Boolean result ) {
    super.onPostExecute(result);
    dia.dismiss();
    callback.update(null, returnFolder);
    System.out.println("Unzipped to: " + returnFolder.getName() );
}

In that case your call of Async Task would look like that:

AsyncUnzip unzipThread = new AsyncUnzip(ImportActivity.this, new Observer() {
    @Override
    public void update( Observable observable, Object data ) {//your code invoked after Async Task
} });
unzipThread.execute(selectedFile); //Start Unzip in external Thread.

Note: This is a quick and diry solution with a annonymous Observer implementation and without an observable.

You can create an Interface and return value from onPostExecute() of AsyncTask or you can register a BroadcastReceiver and fire in from onPostExecute() method of AsyncTask. I had created a demo using Interface and BroadcastReceiver you can download and check it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!