2017-07-25 48 views
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(); 
    } 

誰能幫助從代碼中找出其中可能的錯誤?

+1

您可以使用這一意圖的服務,你會不會需要的AsyncTask爲 – ManishNegi

+0

我用intentService,選中編輯職位,但同樣的問題存在。 –

+0

問題是什麼 – ManishNegi

回答

0

使用報警管理器設置重複報警。

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
    Intent myIntent = new Intent(this, RepeatingService.class); 
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 5000, 5000, pendingIntent); 

RepeatingService使用IntentService因爲當作業完成其自動停止。

class RepeatingService extends IntentService{ 

override fun onHandleIntent(intent: Intent?) { 
    // do your stuff like async or anyother task. 
} 

} 
+0

請檢查編輯後,我用intentService但存在相同的問題。 –