我有一个我正在调用的方法但是,对于较新版本的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();
}
但这不起作用。我究竟做错了什么?另外,如果你注意到我违反了关于HttpClient的任何基本规则,请告诉我。
答案 0 :(得分:2)
您的实现不正确 - 您没有覆盖run()方法
class SendThread extends Thread {
public void run(){
//add your implementation here
}
}
牵开线程
SendThread sendThread = new SendThread();
sendThread.start();
答案 1 :(得分:1)