如何调用AsyncTask的一个返回值的函数函数、返回值、AsyncTask

2023-09-07 01:38:22 作者:我不是最好,但也值得拥有°

我是新来的Andorid程序我刚刚stucked了一个问题调用返回值的函数中的AsyncTask的 doInBackground() 简单的问题是如何等待的AsyncTask完成,然后无严寒UI执行return语句,我也研究了 onPostExecute(),但它并没有解决问题。 下面是示例code

 公共字符串Hello(){
字符串结果= NULL;
 //调用asynctaske execute方法
retrun结果;
}
 

解决方案

对于我自己,我这样做有一个回调函数,我onPostExecute后调用。

 公共AsyncUnzip(活动CTX,观察回调){
    this.ctx = CTX;
    this.callback =回调;
}
 

  @覆盖
在preExecute保护无效(){
    super.on preExecute();
    直径=新ProgressDialog(CTX);
    dia.setTitle(BITTE warten);
    dia.setMessage(Geodatenpaket wird entpackt ......);
    dia.setCancelable(假);
    dia.show();
}
 
AsyncTask研究 以Android 10.0为准

  @覆盖
公共无效onPostExecute(布尔结果){
    super.onPostExecute(结果);
    dia.dismiss();
    callback.update(NULL,returnFolder);
    的System.out.println(解压缩到:+ returnFolder.getName());
}
 

在这种情况下,你的异步任务的调用将看起来像:

  AsyncUnzip unzipThread =新AsyncUnzip(ImportActivity.this,新的观察员(){
    @覆盖
    公共无效更新(可观察观察到,对象数据){//你的code异步任务后调用
}});
unzipThread.execute(selectedFile); //外部线程启动解压。
 

注:这是一个annonymous观察员执行,没有可观察到的一个快速dirY中的解决方案

I am new to andorid programming I've just stucked into a problem to call returning value function inside AsyncTask's doInBackground() Simple question is How to wait for AsyncTask to complete and then execute return statement without freezing UI, i've also studied onPostExecute() but it doesn't solve problem. following is sample code

    public String hello()  {
String result = null;
 //calling asynctaske execute method
retrun result;
}

解决方案

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.

 
精彩推荐
图片推荐