2014-06-04 72 views
2

我需要調用每10秒服務器的REST方法,調用用的AsyncTask一個REST方法每10秒在Android的

,我的意圖是使用的AsyncTask做下列方式:

myTask = new AsyncTask<Void, Void, String>() { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    ... 
    } 

    @Override 
    protected String doInBackground(Void... params) { 
     //invoke REST service 
     .... 
     return ""; 
    } 

    @Override 
    protected void onPostExecute(String response) { 
     super.onPostExecute(response); 
     //post execute operations 
     ... 
    } 
}; 

任何人都可以幫助我嗎?

回答

4

的解決方案是從調用的AsyncTask一個TimerTask

protected class MyTimerTask extends TimerTask { 

    @Override 
    public void run() { 

     (new AsyncTask<Void, Void, String>() { 

      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
       ... 
      } 

      @Override 
      protected String doInBackground(Void... params) { 
       //invoke REST service 
       .... 
       return ""; 
      } 

      @Override 
      protected void onPostExecute(String response) { 
       super.onPostExecute(response); 
       //post execute operations 
       ... 
      } 
     }).execute(); 
    } 
} 

,如果你害怕調用服務器的時間太長,然後要求他們重疊,可以輸入一個的AtomicBoolean信號量(同步)以下列方式:

旗語聲明

private final AtomicBoolean isRunning = new AtomicBoolean(false); 

的TimerTask用旗語

protected class MyTimerTask extends TimerTask { 

    @Override 
    public void run() { 

     //if isRunning is true does not execute the task 
     if (isRunning.get()) return; 

     (new AsyncTask<Void, Void, String>() { 

      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 

       //active flag isRunning 
       isRunning.set(true); 

       ... 
      } 

      @Override 
      protected String doInBackground(Void... params) { 

       .... 
       //invoke REST service 
       .... 
       return ""; 
      } 

      @Override 
      protected void onPostExecute(String response) { 
       super.onPostExecute(response); 
       //post execute operations 
       ... 

       //deactive flag isRunning 
       isRunning.set(false); 
      } 
     }).execute(); 
    } 
} 

注:小心,當你發現一個錯誤,因爲如果由於某種原因仍處於活動狀態將不再運行的AsyncTask

2

考慮使用AlarmManager關閉信號。創建一個服務或廣播接收器來捕獲AlarmManager的意圖併發出您的服務器請求。以下示例說明如何從AlarmManager每10秒建立一次重複事件。

AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
    Intent intent = new Intent(getBaseContext(), AlarmReceiver.class); 
    PendingIntent pending = PendingIntent.getBroadcast(getBaseContext(), 0, intent, 0); 
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), TEN_SECONDS, pending);