0

我有一个正在调用的方法,但是对于较新版本的 Android,它失败了。显然,这是由于缺少线程。我的方法是向我的服务器发送消息。这是代码(无线程)

public String sendMessage(String username, Editable message){
        BufferedReader in = null;
        String data = null;

        try{
            DefaultHttpClient client = new DefaultHttpClient();
            URI website = new URI("http://abc.com/user_send.php?username="+username+"&message="+message);

            HttpPost post_request = new HttpPost();
            post_request.setURI(website);


            HttpGet request = new HttpGet();

            request.setURI(website);
            //executing actual request
            HttpResponse response = client.execute(request);

            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String l = "";
            String nl = System.getProperty("line.separator");
            while ((l = in.readLine()) != null) {
                sb.append(l);

            }
            in.close();
            data = sb.toString();
            return data;
        }catch (Exception e){
            return "ERROR";
        }
    }  

现在,只是想在它周围放一个线程:

    public String sendMessage(String username, Editable message){
        BufferedReader in = null;
        String data = null;
Thread sendThread = new Thread(){
        try{
            DefaultHttpClient client = new DefaultHttpClient();
            URI website = new URI("http://thenjtechguy.com/njit/gds/user_send.php?username="+username+"&message="+message);

            HttpPost post_request = new HttpPost();
            post_request.setURI(website);


            HttpGet request = new HttpGet();

            request.setURI(website);
            //executing actual request
            HttpResponse response = client.execute(request);

            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String l = "";
            String nl = System.getProperty("line.separator");
            while ((l = in.readLine()) != null) {
                sb.append(l);

            }
            in.close();
            data = sb.toString();
            return data;
        }catch (Exception e){
            return "ERROR";
        }
} sendThread.start();   
} 

但这不起作用。我究竟做错了什么?另外,如果您发现我违反了 android 中有关 HttpClient 的任何基本规则,请告诉我。

4

2 回答 2

2

Your implementation is not correct - you did not override run() method

class SendThread extends Thread {
   public void run(){
        //add your implementation here
   }
}

Tow start the thread

SendThread sendThread  = new SendThread();
sendThread.start();
于 2012-04-23T03:31:56.383 回答
1

更好地了解并使用AsyncTask概念。

AsyncTask 允许正确和轻松地使用 UI 线程。此类允许在 UI 线程上执行后台操作并发布结果,而无需操作线程和/或处理程序。请参阅此链接以获取示例实现

于 2012-04-23T03:02:45.407 回答