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

Ali*_*cia 1 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;
}
Run Code Online (Sandbox Code Playgroud)

这输出

"Number of sessions found while trying to get total steps: 0"
"Number of sessions found while reading:  8"
Run Code Online (Sandbox Code Playgroud)

CKi*_*ing 5

有两种解决方案:

选项1:使用阻止集合

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

选项2:使用PendingResult中的await方法

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

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

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

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

公共抽象R等待()

阻止任务完成.UI线程上不允许这样做.返回的结果对象可以具有INTERRUPTED的附加故障模式.

这就是你能做的.而不是将整个调用链接到setResultCallBack,首先调用readSessions:

results = Fitness.SessionsApi.readSession(mGoogleApiClient, readRequest);
Run Code Online (Sandbox Code Playgroud)

然后在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
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

*结果必须声明为实例/类级别变量,才能在类中的所有方法中访问.变量结果是类型PendingResult<SessionReadResults>.此外,看起来您可以取消结果,ArrayList因为您可以从方法SessionReadResults返回的所有内容中提取所需内容await.最后一点,此答案尚未使用您的代码进行测试,因为您的代码示例不完整.