我正在尝试从 Android 获取 GPS 坐标并将其发送到 MySQL 数据库。
一切运行良好,但程序进入无限循环:因为我使用 While (true) 更新 GPS 坐标并每 5 秒将其发送到数据库。
如何避免循环并每 5 秒将坐标发送到数据库中。
这是我的代码:
package com.example.gpstracking;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class AndroidGPSTrackingActivity extends Activity {
Button btnShowLocation;
GPSTracker gps;
double tmplat=0;
double tmplong=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
while (true)
{
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String lat=String.valueOf(latitude);
String lon=String.valueOf(longitude);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("latitude", lat));
postParameters.add(new BasicNameValuePair("longitude", lon));
try {
CustomHttpClient.executeHttpPost("http://plangsm2012.site40.net/new/check.php", postParameters);
} catch (Exception e) {
}
tmplat=latitude;
tmplong=longitude;
}
else{
gps.showSettingsAlert();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}