【发布时间】:2015-04-24 08:39:39
【问题描述】:
我面临着让我发疯的问题。我希望有人能解释我这种奇怪的行为。所以我想将 JSON 字符串 {"latitude":53.86907815,"longitude":10.66554789,"formatted":"23.04.2015 10:16:49","route":4} 传递给我的服务类“PostData”,但同时我在 onStartCommand() 方法中得到 null 以及 JSON 字符串,其中格式化值始终是旧值而不是我传递给班级的当前时间。
MainActivity内部类中的调用部分:
String jSONString = convertToJSON(pLong, pLat, formatted);
Intent intentJson = new Intent(MainActivity.this, PostData.class);
intentJson.putExtra("json_data", jSONString);
startService(intentJson);
PostData 类:
public class PostData extends IntentService {
public PostData() {
super("someone");
// TODO Auto-generated constructor stub
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String jSONString = intent.getStringExtra("json_data");
if(jSONString != null){
System.out.println("Output from onStartCommand "+jSONString);
}
}
}
我也尝试调试它,但是当调试器在 onStartCommand 中时,我总是得到 null 作为输出!!
此屏幕截图是在调试器位于“startService(intentJson);”这一行时捕获的:
这是我在 onStartCommand 方法中得到的一些输出。这里 formatted 始终具有相同的时间戳:23.04.2015 18:37:49 在调试模式中,我总是得到 null 作为输出!!
04-24 11:29:22.785: I/System.out(23721): Output from onStartCommand {"latitude":53.86898202,"longitude":10.66561591,"formatted":"24.04.2015 11:29:23","route":1}
04-24 11:29:22.805: I/System.out(23721): Output from onStartCommand {"latitude":53.86907815,"longitude":10.66554789,"formatted":"23.04.2015 18:37:49","route":4}
04-24 11:29:23.766: I/System.out(23721): Output from onStartCommand {"latitude":53.86898202,"longitude":10.66561589,"formatted":"24.04.2015 11:29:24","route":1}
04-24 11:29:23.806: I/System.out(23721): Output from onStartCommand {"latitude":53.86907815,"longitude":10.66554789,"formatted":"23.04.2015 18:37:49","route":4}
04-24 11:29:24.787: I/System.out(23721): Output from onStartCommand {"latitude":53.868982,"longitude":10.66561591,"formatted":"24.04.2015 11:29:25","route":1}
04-24 11:29:24.807: I/System.out(23721): Output from onStartCommand {"latitude":53.86907815,"longitude":10.66554789,"formatted":"23.04.2015 18:37:49","route":4}
04-24 11:29:25.758: I/System.out(23721): Output from onStartCommand {"latitude":53.868982,"longitude":10.66561591,"formatted":"24.04.2015 11:29:26","route":1}
04-24 11:29:25.818: I/System.out(23721): Output from onStartCommand {"latitude":53.86907815,"longitude":10.66554789,"formatted":"23.04.2015 18:37:49","route":4}
04-24 11:29:26.809: I/System.out(23721): Output from onStartCommand {"latitude":53.86907815,"longitude":10.66554789,"formatted":"23.04.2015 18:37:49","route":4}
【问题讨论】:
-
你为什么要覆盖 onStartCommand?我不是说它会解决你的问题,但你所需要的只是覆盖 onHandleIntent
-
@pskink:我已经将代码移到了 onHandleIntent() 方法,但我现在得到了一个当前时间
24.04.2015 11:21:36和一个旧时间23.04.2015 18:37:49" -
所以你 startService 一次但 onHandleIntent 被调用两次? strrrrrrrrrrange....