2015-04-19 76 views
1

所以我是Android的小菜鳥,我正在編寫一個簡單的應用程序,使用Google Fit來存儲用戶健身會話和步數,然後檢索它們。如何在繼續(Android)之前等待結果回調完成的方法?

我有兩種方法,一種是從雲中獲取給定日期範圍內的所有會話,下一個方法遍歷這些方法並累計步數。

問題是,雖然我首先調用提取方法,但結果直到我添加了這些步驟後才返回,所以步數始終爲零。

這裏是我的代碼:

private ArrayList<> results; 

    @Override 
    public ArrayList<IndividualSession> readAllSessions(Date dateFrom, Date dateTo) { 

    /* I haven't included the following code in this question just to keep things clean, but here there was 
     - The initialisation of the results ArrayList 
     - Creating the calendar and date objects 
     - Building the session read request 
    */ 

    Fitness.SessionsApi.readSession(mGoogleApiClient, readRequest).setResultCallback(new ResultCallback<SessionReadResult>() { 
     @Override 
     public void onResult(SessionReadResult sessionReadResult) { 
      for (Session session : sessionReadResult.getSessions()) { 
       List<DataSet> dataSets = sessionReadResult.getDataSet(session); 
       for (DataSet dataSet : dataSets) { 
        for (DataPoint dataPoint : dataSet.getDataPoints()) { 
        // Create new IndividualSession object, add data to it then add it to arraylist 
         IndividualSession individualSessionObject = new IndividualSession(); 
         individualSessionObject.setFromDate(new Date(session.getStartTime(TimeUnit.SECONDS))); 
         individualSessionObject.setToDate(new Date(session.getEndTime(TimeUnit.SECONDS))); 
         individualSessionObject.setStepCount(dataPoint.getValue(Field.FIELD_STEPS).asInt()); 
         results.add(individualSessionObject); 
        } 
       } 
      } 
      Log.i(TAG, "Number of sessions found while reading: "+results.size()); 
     } 
    }); 
    return results; 
} 



@Override 
public int getDaySteps(Date dateTo) { 
    int stepCount = 0; // to be returned 

    // Sort out the dates 
    Calendar calFrom = Calendar.getInstance(); 
    calFrom.add(Calendar.HOUR, -24); 

    // Get the sessions for appropriate date range 
    ArrayList results = readAllSessions(calFrom.getTime(), dateTo); 
    Log.i(TAG, "Number of sessions found while trying to get total steps: "+results.size()); 

    // Iterate through sessions to get count steps 
    Iterator<IndividualSession> it = results.iterator(); 
    while(it.hasNext()) 
    { 
     IndividualSession obj = it.next(); 
     stepCount += obj.getStepCount(); 
    } 
    return stepCount; 
} 

此輸出

"Number of sessions found while trying to get total steps: 0" 
"Number of sessions found while reading: 8" 
+0

你在哪裏試圖「等待」?調用'readAllSessions'後? –

+0

我試圖在內部等待public int getDaySteps(Date dateTo)'''我需要等待'''readAllSessions(calFrom.getTime(),dateTo);'''在繼續之前返回一個值 – Lissy

+0

@VinceEmigh我認爲沒有必要明確地做到這一點。我瀏覽了文檔,API提供了一個機制來等待結果。 – CKing

回答

5

有兩個解決辦法:

方法1:使用阻塞colleciton

  1. ArrayList<> results更改爲ArrayBlockingQueue<> results
  2. 調用在getDaySteps方法readAllSessions方法後,調用while(results.take()!=null) { //rest of the logic }
  3. 你需要某種mechanistm的退出while循環在步驟2中,當所有的結果都讀

選項2:使用來自PendingResult的等待方法

查看SessionsAPI類的文檔,readSessions方法似乎返回PendingResult:

公共抽象PendingResult readSession (GoogleApiClient客戶端,SessionReadRequest請求)

從特定類型 的用戶的谷歌適合存儲和用於從所述請求參數中選擇的特定的會話(一個或多個)讀取數據。

尋找在PendingResult類的AWAIT方法的文檔:

公共抽象ř等待()

塊,直到任務完成。這在UI線程中是不允許的。返回的結果對象可能具有中斷的附加故障模式 。

這是你可以做的。

results = Fitness.SessionsApi.readSession(mGoogleApiClient, readRequest); 

然後等待結果的getDaySteps方法:而是鏈接到setResultCallBack整個呼叫,第一個呼叫readSessions的

SessionReadResults sessionResults = results.await(); 
for (Session session : sessionReadResult.getSessions()) { 
     List<DataSet> dataSets = sessionReadResult.getDataSet(session); 
     for (DataSet dataSet : dataSets) { 
      for (DataPoint dataPoint : dataSet.getDataPoints()) { 
      // Create new IndividualSession object, add data to it then add it to arraylist 
       IndividualSession individualSessionObject = new IndividualSession(); 
       individualSessionObject.setFromDate(new Date(session.getStartTime(TimeUnit.SECONDS))); 
       individualSessionObject.setToDate(new Date(session.getEndTime(TimeUnit.SECONDS))); 
      individualSessionObject.setStepCount(dataPoint.getValue(Field.FIELD_STEPS).asInt()); 
        //use the results 
      } 
     } 
    } 

*結果必須聲明爲實例/類級別變量可以在課堂上的所有方法中使用。變量結果爲PendingResult<SessionReadResults>。此外,看起來你可以取消結果ArrayList,因爲你想要的東西都可以從await方法返回的SessionReadResults中提取。最後一個註釋,這個答案還沒有用你的代碼進行測試,因爲你的代碼樣本不完整。

相關問題