我对 Android 比较陌生。我正在尝试使用 AsyncTask 但在执行线程后,我的应用程序强制我关闭它。在我的异步线程中,我在服务器端执行 php,它保存来自 Android 传感器的数据。任何帮助将不胜感激。谢谢
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
final FuncionsActivity functions = new FuncionsActivity();
if(something)
functions.execute(nameValuePairs);
.....
}
private class FuncionsActivity extends
AsyncTask<ArrayList<NameValuePair>, Integer, Integer > {
@Override
protected Integer doInBackground(ArrayList<NameValuePair>... data) {
// 1) Connect via HTTP. 2) Encode data. 3) Send data.
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://.../saveCoordinates.php");
//HttpPost httppost = new
httppost.setEntity(new UrlEncodedFormEntity(data[0]));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
this.onPostExecute(null);
//Could do something better with response.
}
catch(Exception e)
{
Log.e("log_tag", "Error1: " + e.toString());
}
return 0;
}
protected void onProgressUpdate(Integer... item){
Log.d("TestP", item[0] + " item has been processed");
}
protected void onPostExecute(Integer result){
Log.d("TestP", "AsyncTask returned : " + result);
}
}
@Override
protected void onDestroy() {
super.onDestroy(); // Move to bottom
//System.runFinalizersOnExit(true);
}
}