2017-07-25 215 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但存在相同的问题。 –