android – 如何从异步任务返回结果

前端之家收集整理的这篇文章主要介绍了android – 如何从异步任务返回结果前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参见英文答案 > How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?                                    16个
我一直在使用异步任务来访问Web服务器并使用结果更新控件.这有缺点,即它使异步方法特定于控制并使我再次使用返回的字符串.

如何从异步调用onPostExecute返回结果字符串?我怎么称呼它?我似乎无法让我的代码能够做到这一点.线程应该没有问题,因为我有一个冻结UI的对话框,直到完成工作.

我的典型asyncTask代码如下

class GetDataFromServer extends AsyncTaskPHP";

    public myAsyncMethos(String dialogMessage,Context con)
    {
        this.qDialog =  new ProgressDialog(con);
        this.dialogString = dialogMessage;
        this.context = con;
    }

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        qDialog = new ProgressDialog(this.context);
        qDialog.setMessage(this.dialogString);
        qDialog.setIndeterminate(false);
        qDialog.setCancelable(false);
        qDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args)
    {
        //MAKE SERVER CALL and cast to JSONOBject

        return jsonNewUser;
    }

    public void onPostExecute(JSONObject jsonString)
    {

         // dismiss the dialog after getting response
        qDialog.dismiss();
//I WANT TO RETURN A STRING HERE BUT KEEP GETTING Syntax ERRORS BEFORE RUNTIME


    }
}
最佳答案
我个人会在你的类中添加一个回调函数,然后运行onPostExecute后,关闭你对主类的监听器的回调.

class GetDataFromServer extends AsyncTask

然后从你的通话类,你会有这样的东西……

    private void callTheAsyncThing
    {
        GetDataFromServer gds=new GetDataFromServer("please wait",this,letMeKnow);
        gds.execute(params);
    }

    private InformComplete letMeKnow=new InformComplete()
    {
        public void PostData(JSONObject result)
        {
            // we now have the data in the calling class
        }
    };

猜你在找的Android相关文章