简体   繁体   English

执行其余代码后,Asyc任务完成了吗?

[英]Asyc task finishing after execution of rest of code?

I am sending HTTP request to server using AsnncTask.I am calling one function checkServer() with three arguments. 我正在使用AsnncTask向服务器发送HTTP请求。我正在调用一个带有三个参数的函数checkServer() From this function i am calling a class URLDataProvider().execute("url").get(). 通过此函数,我正在调用类URLDataProvider()。execute(“ url”)。get()。

When i call checkServer then asynctask is called but after getting response code of 404 checkProtocol method is called. 当我调用checkServer将调用checkServer但在获取404响应代码后,将调用checkProtocol方法。 after that OnPostExecute method is called. 之后调用OnPostExecute方法。

After that i again calling checkServer() from Post execute if response code is 404. But the rest of code is called and after that i get the response code of 200 Ok. 之后,如果响应代码为404,我再次从Post调用checkServer() 。但是,其余代码被调用,之后我得到200 Ok的响应代码。 May i know why checkProtocol() & rest of the code is called before the end of checkServer() . 我可以知道为什么在checkServer()结束之前调用checkProtocol()和其余代码。

Here is the code 这是代码

checkServer("http","servername","firstlogin");

checkProtocol(host_ip, portnumber);
-----------Some code-------------
 new Thread(new Runnable(){

URL DATA PROVIDER URL数据提供者

private class UrlDataProvider3 extends AsyncTask<String, Void, String>
{

    String ret="";
    int checkStatus;
    Boolean exception=false;

    @Override
    protected String doInBackground(String... url) 
    {

        HttpURLConnection con = null;

        try 
          { 

            HttpURLConnection.setFollowRedirects(true);
            con = (HttpURLConnection) new URL(url[0]).openConnection();
                con.setRequestMethod("HEAD");
                con.setConnectTimeout(20000);



            if(con.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND && con.getURL().toString().contains("pdata/Login"))
            {

                checkStatus=1;
                return "done";

            }
            else if(con.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND && con.getURL().toString().contains("cdata/Login"))
            {

                 checkStatus=2;
                 return "done";
            }

            if(con.getResponseCode()==HttpURLConnection.HTTP_OK && con.getURL().toString().contains("pdata/Login"))

            {


                return "done";


            }
            else if(con.getResponseCode()==HttpURLConnection.HTTP_OK && con.getURL().toString().contains("cdata/Login"))
            {



                return "done";

            }

          }

        catch (SocketTimeoutException ste)
        {

            con.disconnect();
            return null;
        }
        catch (IOException e)
          {





          }

    return ret;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);



         if(checkStatus==1)
            {
                if(SettingsChaned)
                {

                 checkServer("http", "cdata","thirdlogin");
                }
                else 
                {

                checkServer("http", "cdata","firstlogin");
                }

            }
            else if(checkStatus==2)
            {
                if(SettingsChaned)
                {

                checkServer("http", "pdata","thirdlogin");
                }
                else
                {

                checkServer("http", "pdata","firstlogin");
                }
            }

}

AsynTask will move your execution to another thread and your so called rest of code is written in UI thread and it will be called before AsynTask is completed. AsynTask会将您的执行移至另一个线程,您所谓的其余代码将写在UI线程中,并且它将在AsynTask完成之前被调用。

If you want to execute rest of code after AsynTask do its job you should write that rest of code in onPostExecute 如果要在AsynTask完成工作后执行其余代码,则应在onPostExecute中编写其余代码

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
        // background task
     }



     protected void onPostExecute(Long result) {
        // rest of code
     }
 } 

Change the parameters of AsyncTask accordindly 一致地更改AsyncTask的参数

"AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. “ AsyncTask可以正确且轻松地使用UI线程。此类允许执行后台操作并在UI线程上发布结果,而无需操纵线程和/或处理程序。

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTask被设计为围绕Thread和Handler的帮助器类,并且不构成通用的线程框架。 AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask." 理想情况下,应将AsyncTasks用于较短的操作(最多几秒钟)。如果需要使线程长时间运行,则强烈建议您使用java.util.concurrent包提供的各种API,例如执行器,ThreadPoolExecutor和FutureTask。”

With this in mind remeber if you have lines of code outside of the AsynTask for example 考虑到这一点,请记住,例如,如果您在AsynTask之外有代码行

{
    new LongOperation().execute(""); //This runs in another thread on its doInBackground() method
    showAToast(); //this is still in the main thread.
    //And so on...
}

the showToastMethod will run on the Main thread while the LongOperation() AsyncTask wil continue in another thread. showToastMethod将在Main线程上运行,而LongOperation()AsyncTask将在另一个线程中继续运行。

For a more in dept with lots of examples you can go to: The Documentation here 有关更多示例的详细信息,请访问: 此处的文档

Hope it clears your doubt. 希望它清除您的疑问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM