线程和异步任务在http post中的使用

3

朋友们,我需要帮助,使用Asynctask或Threads将Android httppost数据发送到服务器。当我点击发布按钮时,需要将数据发送到我的服务器。但是当我点击它时,应用程序需要进入下一页,并且数据需要通过后台进程发送。我是Android的新手。我不知道这种任务应该使用什么(Threads还是Asyanctask)。我尝试了这个代码,但它会给我异常错误。

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();
            }
    }

但如果我这样使用它,它就可以工作了。(text是该页面上的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()函数? - GVillani82
3个回答

5
你可以使用 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();
    }   
}  

并且您需要将以下代码放入您的主方法中:

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

看这里。 希望这能帮助你。


1
我建议您使用Robospice其他框架作为替代方案
  • Volley

  • DataDroid

  • REST Provider

  • REST Droid

  • PostMan (响铃两次) Lib

  • Ion

  • droidQuery

  • Android Job Queue

  • Goro

    因为在达到onPostExecute之前可能会重新创建活动。 AsyncTask不是Activity中进行网络操作的好例子。


1
你应该实现类似这样的代码:
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方法会将Runnable添加到消息队列中。该runnable将在用户界面线程上运行。 [参考资料] 这是必需的,因为如果没有此方法,您将违反单线程模型:Android UI工具包不是线程安全的,必须始终在UI线程上进行操作。在您的代码片段中,TextView在工作线程上被操作,这可能会导致非常奇怪的问题。
正如您所看到的,如果您的线程内部方法需要访问UI,则应使用.post方法,这会使代码更加繁琐。因此,正确的解决方案可能是使用AsyncTask,它将为您管理线程的复杂性。您必须将需要访问UI的代码放在onPostExecute()方法中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接