【发布时间】:2017-12-31 04:54:41
【问题描述】:
我想每 5 秒后从 web 服务请求 json 数据。因为我不想向用户展示,所以我在服务中做这些事情。代码中没有错误,但没有按预期在日志中显示任何输出。
代码如下:
protected void onHandleIntent(Intent intent) {
final String driverId = intent.getStringExtra("DriverId");
new Handler().postDelayed(new Runnable() {
public void run() {
HttpHandler sh = new HttpHandler();
// making request to url and getting respose
String jsonStr = sh.makeServiceCall(url + "?cno=" + driverId + "&lat=0&lon=79");
Log.e("ServicesClass", "Response from url: " + jsonStr);
if (jsonStr != null) {
String temp = jsonStr;
String finals = temp.replace("<string xmlns=\"http://tempuri.org/\">", "");
Log.e(TAG, "Response from url at Service Class: " + jsonStr);
} else {
Log.e(TAG, "Response from url at Service Class: " + jsonStr);
}
}
}, 5000);
}
makeServiceCall 的代码:
public String makeServiceCall(String reqUrl){
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
//read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
}catch (MalformedURLException e){
Log.e(TAG, "MalformedException: " +e.getMessage());
}catch (ProtocolException e){
Log.e(TAG, "Protocal Exception: " +e.getMessage());
}catch (IOException e){
Log.e(TAG, "IOException: " +e.getMessage());
}catch (Exception e){
Log.e(TAG, "Exception: " +e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is){
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null){
sb.append(line).append('\n');
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
is.close();
}catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
谁能帮忙从代码中找出可能出错的地方?
【问题讨论】:
-
您可以为此使用 Intent 服务,并且您不需要为此使用 asyncTask
-
我使用了intentService,检查编辑过的帖子,但同样的问题存在。
-
有什么问题
-
如您所见,我正在记录 Log.e("ServicesClass", "Response from url:" + jsonStr);但在 logcat 中没有可见的日志,这意味着代码没有执行或其他我无法弄清楚的东西
-
在
makeServiceCall()中添加日志记录或设置断点并单步执行。您需要缩小问题所在的范围。从您发布的代码中看不出任何明显的东西。
标签: java android json web-services android-service