0
我想每5秒钟向web服务请求json数据。因为我不想向用户展示,所以我在Service中做这些事情。代码中没有错误,但没有按预期在Log中显示任何输出。Android:如何通过服务每5秒发送一次http请求
下面是代码:
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();
}
谁能帮助从代码中找出其中可能的错误?
您可以使用这一意图的服务,你会不会需要的AsyncTask为 – ManishNegi
我用intentService,选中编辑职位,但同样的问题存在。 –
问题是什么 – ManishNegi