我正在尝试将JSON字符串传递给Service类,但我注意到时间正在改变(在onHandelIntent方法中)并且我总是得到一个旧的timeStamp。我已经清理了我的项目,但没有任何改变。
这个部分是从内部类" MyLocationListener"中的onLocationChanged方法调用的。在MainActivity中:
public void onLocationChanged(Location location) {
if (location != null) {
double pLong = location.getLongitude();
double pLat = location.getLatitude();
SimpleDateFormat sdf = new SimpleDateFormat(
"dd.MM.yyyy HH:mm:ss", java.util.Locale.getDefault());
String formatted = sdf.format(location.getTime());
// If I pass the data like this it works but I have to add a constructor
// for the class and work with Thread as well as AsyncTask.
// String jSONString = convertToJSON(pLong, pLat, formatted);
// PostData sender = new PostData(jSONString);
// sender.timer();
String jSONString = convertToJSON(pLong, pLat, formatted);
Intent intent3 = new Intent(MainActivity.this, PostData.class);
intent3.putExtra("json_data", jSONString);
// Here I am getting the right timeStamp.
startService(intent3);
}
convertToJSON方法:
private String convertToJSON(double pLong, double pLat, String formatted) {
//envelop the data in JSON format.
Data d = new Data(pLat, pLong, formatted,route_number);
Gson gson = new GsonBuilder().registerTypeAdapter(Data.class, new DataSerializer()).create();
String a = gson.toJson(d);
return a;
}
PostData类:
public class PostData extends IntentService {
public PostData() {
super("some");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
String jSONString = intent.getStringExtra("json_data"); //here I am always getting this time "18:37:49"
}
}
onHandelIntent()中传递的JSON字符串:
{
"latitude":47.86907815,
"longitude":13.66554789,
"formatted":"23.04.2015 18:37:49",
"route":4
}