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