如何在继续之前等待结果回调的方法完成(Android)?

时间:2015-04-19 17:05:21

标签: java android

所以我是Android的菜鸟,我正在编写一个简单的应用程序,它使用Google Fit存储用户健身会话和步数,然后检索它们。

我有两种方法,一种方法从云中获取给定日期范围内的所有会话,下一种方法迭代这些方法并累计步数。

问题是,虽然我首先调用了抓取方法,但是在我添加了步骤之后结果才会回来,因此步数始终为零。

这是我的代码:

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"

1 个答案:

答案 0 :(得分:5)

有两种解决方案:

选项1:使用阻止收集

  1. ArrayList<> results更改为ArrayBlockingQueue<> results
  2. readAllSessions方法中调用getDaySteps方法后,请致电while(results.take()!=null) { //rest of the logic }
  3. 当读取所有结果时,您需要某种机制来退出步骤2中的while循环
  4. 选项2:使用PendingResult中的await方法

    查看SessionsAPI类的文档,readSessions方法似乎返回了PendingResult:

      

    公共抽象PendingResult readSession   (GoogleApiClient客户端,SessionReadRequest请求)

         

    从用户的Google Fit商店中读取特定类型的数据   以及从请求参数中选择的特定会话。

    查看PendingResult类中await方法的文档:

      

    public abstract R await()

         

    阻止任务完成。 UI线程上不允许这样做。返回的结果对象可以具有其他故障模式   中断。

    这是你可以做的。而不是将整个调用链接到setResultCallBack,首先调用readSessions:

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

    然后在getDaySteps方法中等待结果:

    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,因为您可以从SessionReadResults方法返回的await中提取所需内容。最后一点,这个答案尚未使用您的代码进行测试,因为您的代码示例不完整。