我正在使用一个应用程序,我只需要从mysql服务器下载谷歌地图的一对坐标。我可以使用PHP和普通的httpost成功完成此操作,但是当我这样做时,我的应用程序会冻结几秒钟。
我读到你需要使httppost asycronous,以避免冻结,直到服务器完成prossess并发送结果。
关键是我需要的结果是json数组,就像普通的httpost。
例如,如果我有这个httppost。
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
String result11 = null;
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is11, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is11.close();
result11 = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parsing data
try {
JSONArray jArray1 = new JSONArray(result11);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
如何将其转换为异步帖子以便我可以避免冻结?
答案 0 :(得分:5)
有一个很好的类AsyncTask
,可用于轻松运行异步任务。如果您将代码嵌入到这样的子类中,您最终可能会得到:
public class FetchTask extends AsyncTask<Void, Void, JSONArray> {
@Override
protected JSONArray doInBackground(Void... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
String result11 = sb.toString();
// parsing data
return new JSONArray(result11);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(JSONArray result) {
if (result != null) {
// do something
} else {
// error occured
}
}
}
您可以使用以下方式启动任务:
new FetchTask().execute();
其他资源:
答案 1 :(得分:3)
我建议使用android-async-http(http://loopj.com/android-async-http/)库。它使android异步http调用简单而优雅。
答案 2 :(得分:2)
不仅仅是开始一个新线程,最好还是选择一个成熟的AsyncTask。它可以更好地控制事物。
private class DoPostRequestAsync extends AsyncTask<URL, Void, String> {
protected String doInBackground(URL url) {
//Your download code here; work with the url parameter and then return the result
//which if I remember correctly from your code, is a string.
//This gets called and runs ON ANOTHER thread
}
protected void onPostExecute(String result) {
//This gets called on the interface (main) thread!
showDialog("Done! " + result);
}
}
将新类实现放在所需Activity类的内部。有关AsyncTask的更多信息,请点击此链接:
http://developer.android.com/reference/android/os/AsyncTask.html
答案 3 :(得分:1)
假设您想在按钮上执行此操作:
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
//your code here
}
}).start();
}
基本上,您将IO密集型操作放在一个单独的线程(而不是您的UI线程)中,以便UI不会冻结。
答案 4 :(得分:1)
使用像ion这样的异步http库。 https://github.com/koush/ion
将为您处理所有线程和异步样板。
这是使用Ion的异步代码。更简单:
Ion.with(context)
.load("http://www.yoursite.com/script.php")
.setBodyParameter("id", "12345")
.setBodyParameter("stringdata", "AndDev is Cool!")
.asJsonArray()
.setCallback(new FutureCallback<JsonArray> {
void onCompleted(Exception e, JsonArray result) {
// do something with the result/exception
}
});