OnPostExecute未在AsyncTask(C#)中执行

时间:2014-10-31 10:28:27

标签: c# android android-asynctask xamarin

我在Xamarin Studio中制作Android应用程序,但OnPostExecute()未执行。

DoInBackground()方法中,我有这个:

protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] native_parms) {
    System.IO.Stream ins = null;
    try {
        URL url = new URL(this.url);
        HttpURLConnection conn = (HttpURLConnection) url.OpenConnection();
        conn.ReadTimeout = 10000;
        conn.ConnectTimeout = 15000;
        conn.RequestMethod = "GET";
        conn.DoInput = true;
        conn.DoOutput = true;

        Dictionary<string, string> queryParams = new Dictionary<string, string>();
        queryParams.Add("username", this.username);
        queryParams.Add("password", this.password);

        System.IO.Stream os = conn.OutputStream;
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        // getQueryString() just builds a query string
        writer.Write(getQueryString(queryParams));

        writer.Flush();
        writer.Close();
        os.Close();

        // Starts the query
        conn.Connect();
        int response = (int) conn.ResponseCode;
        System.Console.WriteLine(response);
        ins = conn.InputStream;

        // Convert the InputStream into a string
        String contentAsString = read(ins, conn.ContentLength);
        System.Console.WriteLine("Done the task.");
        return contentAsString;

        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    }
    finally {
        if (ins != null) {
            ins.Close();
        }
    }
}

然后这就是OnPostExecute()方法:

protected override void OnPostExecute(AsyncTaskResult<bool, Error> result) {
    System.Console.WriteLine("On post execute");
}

我只是调用AsyncTask.execute()方法。

猜猜看,这是输出:

Done the task.

为什么?而且,更重要的是,我该如何解决它?

2 个答案:

答案 0 :(得分:0)

我(仍)不知道为什么它不能使用类型参数。但是,为了使工作正常,您只需要删除泛型部分:

public class YourTask : AsyncTask { ... }

然后按Java.Lang.Object替换所有出现的发布,进度或结果参数:

protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] parms) { ... }

protected override void OnPostExecute(Java.Lang.Object result) { ... }

答案 1 :(得分:0)

以下是一个具有通用AsyncTask的示例。我不知道你的问题究竟是什么,因为你还没有显示所有相关的代码。也就是说,重写OnPostExecute(AsyncTaskResult结果)乍一看对我来说是错误的 - 请注意我的版本使用TResult作为parmater类型(在我的情况下为int)。

public class MyTask: AsyncTask<string, int, int>
    {
        protected MyTask(IntPtr javaReference, JniHandleOwnership transfer)
            : base(javaReference, transfer)
        {

        }
        public MyTask()
        {

        }

        protected override int RunInBackground(params string[] @params)
        {
            return 4;
        }

        protected override void OnPostExecute(int result)
        {
            System.Console.WriteLine("On post execute");
            base.OnPostExecute(result);
        }
    }