2013-10-27 138 views
7

我需要每10秒從服務器接收一個狀態。Android:如何每10秒通過服務發送http請求

我試圖通過服務發送一個http請求來做到這一點。

問題是我的代碼只執行一次。

這是我的服務代碼:

public class ServiceStatusUpdate extends Service { 

@Override 
public IBinder onBind(Intent intent) { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    while(true) 
    { 
     try { 
      Thread.sleep(10000); 
     } catch (InterruptedException e) { 
      new DoBackgroundTask().execute(Utilities.QUERYstatus); 
      e.printStackTrace(); 
     } 
     return START_STICKY;    
    } 
} 

private class DoBackgroundTask extends AsyncTask<String, String, String> { 

    @Override 
    protected String doInBackground(String... params) { 
     String response = ""; 
     String dataToSend = params[0]; 
     Log.i("FROM STATS SERVICE DoBackgroundTask", dataToSend); 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(Utilities.AGENT_URL); 

     try { 
      httpPost.setEntity(new StringEntity(dataToSend, "UTF-8")); 

      // Set up the header types needed to properly transfer JSON 
      httpPost.setHeader("Content-Type", "application/json"); 
      httpPost.setHeader("Accept-Encoding", "application/json"); 
      httpPost.setHeader("Accept-Language", "en-US"); 

      // Execute POST 
      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity responseEntity = httpResponse.getEntity(); 
      if (responseEntity != null) { 
       response = EntityUtils.toString(responseEntity); 
      } else { 
       response = "{\"NO DATA:\"NO DATA\"}"; 
      } 
     } catch (ClientProtocolException e) { 
      response = "{\"ERROR\":" + e.getMessage().toString() + "}"; 
     } catch (IOException e) { 
      response = "{\"ERROR\":" + e.getMessage().toString() + "}"; 
     } 
     return response; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     Utilities.STATUS = result; 
     Log.i("FROM STATUS SERVICE: STATUS IS:", Utilities.STATUS); 
     super.onPostExecute(result); 
    } 
} 
} 

感謝的很多 阿維

回答

15

裏面放onPostExecute處理程序後10秒

new Handler().postDelayed(new Runnable() { 
     public void run() { 
      requestHttp(); 
     } 
    }, 10000); 

發送HTTP請求後10秒doInBackground將再次執行一遍onPostExecute後,再處理等等等等..

+0

謝謝大家 這樣做了。 –

1

您可以簡單地使用CountDownTimer類機器人。

public class AlertSessionCountDownTimer extends CountDownTimer { 

    public AlertSessionCountDownTimer(long startTime, long interval) { 
     super(startTime, interval); 
    } 

    @Override 
    public void onFinish() { 
     //YOUR LOGIC ON FINISH 10 SECONDS 
    } 

    @Override 
    public void onTick(long millisUntilFinished) { 
     //YOUR LOGIC ON TICK 
    } 
} 

希望它能幫助你。

+0

onFinish()您可以將廣播消息發送到任何類將調用Web服務或做一些東西和更新數據..它取決於您的要求,你要如何實現它。 :-) –

0

代碼只運行一次的原因是您的計時器循環中有return。不過,我建議將循環移至後臺任務,或者使用此處給出的其他答案之一,而不是在不會返回的onStartCommand()中執行循環。

0
Handler handler_proc = new Handler(); 

final Runnable runnable_proc = new Runnable() { 
    public void run() { 
     requestHttp(new OnFinish() { 
      @Override 
      public void onSuccess() { 
       // pause should be considered since the end of the previous http request. 
       // Otherwise, new requests will occur before the previous one is complete, 
       // if http_timeout > delay 
       handler_proc.postDelayed(runnable_proc, 10000); 
      } 
     }); 
    } 
} 

handler_proc.post(runnable_proc); 
0

put return START_STICKY; 之後,服務將正常工作

+0

您可以更具體地瞭解這將做什麼,以及它對應用程序的影響。 – JamesENL