【问题标题】:Threads and Asynctask task use for httpposthttppost 的线程和 Asynctask 任务使用
【发布时间】:2013-10-01 19:19:15
【问题描述】:

朋友们,我需要帮助来使用 Asynctask 或 Threads 将 android httppost 数据发送到服务器 当我单击发布按钮时,我需要将数据发送到我的服务器。但是当我单击它时,应用程序需要转到下一页并且数据需要作为后台进程发送。我是 Android 新手。我不知道是什么完全用于这种任务(线程或 Ayanctask)。 我试过这段代码,但它会给我异常错误

public void startProgress(final String name) {
        // Do something long
        Runnable runnable = new Runnable() {
            @Override
            public void run() {               
               try {
                   Thread.sleep(500);
                   send(name);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

             }
        };
        new Thread(runnable).start();
    }


    public void send(String name)
    {
        // get the message from the message text box
           HttpClient httpclient = new DefaultHttpClient();
           HttpPost httppost = new HttpPost("http://10.0.2.2:8080/Test");
           try {
                 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                 String co2 =input_field.getText().toString(); 
                 nameValuePairs.add(new BasicNameValuePair("Name", name));
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                 Toast toast = Toast.makeText(getApplicationContext(), "Got it ", Toast.LENGTH_SHORT);
                 toast.show();
                 httpclient.execute(httppost);
                 input_field.setText("");
            } catch(Exception e){
                 Toast toast2 = Toast.makeText(getApplicationContext(),  "error", Toast.LENGTH_SHORT);
                 toast2.show();
            }
    }

但如果我以这种方式使用它,它可以工作。(文本是该页面中的 TextView 项)

public void startProgress(final String name) {
        // Do something long
        Runnable runnable = new Runnable() {
          @Override
          public void run() {



               try {
                Thread.sleep(500);

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


             text.post(new Runnable() {
                @Override
                public void run() {

                    send(name);
                }
              });
            }


        };
        new Thread(runnable).start();
      }

下面这段代码发生了什么,你能解释一下吗

text.post(new Runnable() {
                    @Override
                    public void run() {

                        send(name);
                    }
                  });

请帮我解决这个问题。如果有更好的方法来满足我的需要,请提到它。因为它对Android开发的经验非常少

【问题讨论】:

  • 为什么你在其他 run() 中使用 run() ?

标签: android multithreading android-asynctask http-post


【解决方案1】:

您可以像这样使用AsyncTask 来做到这一点:

public class HttpPostExanple extends AsyncTask<String, Void, String> 
{       

    @Override
    protected String doInBackground(String... params)   
    {           
        BufferedReader inBuffer = null;
        String url = "http://10.0.2.2:8080/Test";
        String result = "fail";
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost request = new HttpPost(url);
            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("name", params[0]));

            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
                    postParameters);

            request.setEntity(formEntity);
             httpClient.execute(request);
                    result="got it";

        } catch(Exception e) {
            // Do something about exceptions
            result = e.getMessage();
        } finally {
            if (inBuffer != null) {
                try {
                    inBuffer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return  result;
    }

    protected void onPostExecute(String page)
    {       
        //textView.setText(page); 
        Toast toast = Toast.makeText(getApplicationContext(), page, Toast.LENGTH_SHORT);
      toast.show();
    }   
}  

你需要在你的 main 方法中有这个

new HttpPostExample().execute(new String[] {name}); 

看看这个。 希望这会对你有所帮助。

【讨论】:

    【解决方案2】:

    你应该实现这样的东西:

    new Thread(new Runnable() {
        public void run() {
          send(name); // if this method need to access the UI interface you have to use .post method 
        }
      }).start();
    

    关于你的问题:.post 方法causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread. [reference]

    这是必需的,因为如果没有这种方法,您将违反单线程模型:the Android UI toolkit is not thread-safe and must always be manipulated on the UI thread. 在您的代码中,TextView 是在工作线程上操作的,这可能会导致非常奇怪的问题。

    如您所见,如果您的线程中的方法需要访问 UI,您应该使用 .post 方法,这会使代码更加费力。因此,正确的解决方案可能是使用 AsyncTask,它将为您管理线程的复杂性。您必须将需要访问的部分代码放在 UI 上,在 onPostExecute() 方法中

    【讨论】:

      【解决方案3】:

      我建议你使用robospiceother frameworks as alternative

      • 排球

      • 数据机器人

      • REST 提供者

      • 休息机器人

      • 邮递员(响两次)Lib

      • 离子

      • 机器人查询

      • Android 作业队列

      • 五郎

        因为可以在达到onPostExecute 之前重新创建活动。 AsyncTask 不是 Activity 中网络的好例子。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-30
        • 2018-04-12
        • 1970-01-01
        相关资源
        最近更新 更多