朋友们,我需要帮助将 android httppost 数据使用 Asynctask 或 Threads 发送到服务器,当我单击发布按钮时,我需要将数据发送到我的服务器。但是当我单击它时,应用程序需要转到下一页,并且数据需要作为后台进程发送.我是 Android 新手。我不知道这种任务(线程或 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();
}
}
但如果我以这种方式使用它,它就可以工作。(文本是该页面中的 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开发的经验非常少