2016-01-26 47 views
0

我目前正試圖通過我的應用程序顯示今天的當前步驟。我有下面的代碼,其中大部分時間都是正確的。我也已將SHA1證書添加到開發者控制檯。Google fit history API不會檢索數據集?

  1. 我不斷收到錯誤「插入數據集時出現問題。」在我登錄之後,沒有其他的事情出現後,我有點困惑,爲什麼?

  2. 此外,這似乎是脾氣暴躁,有時它的工作原理和顯示隨機數7個數據集(不是我的步數),所以我的第二個問題是我如何才能讓它顯示在今天?

認證

private void buildFitnessClient() { 
    if (mClient == null) { 
     mClient = new GoogleApiClient.Builder(this) 
       .addApi(Fitness.HISTORY_API) 
       .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ)) 
       .addConnectionCallbacks(
         new GoogleApiClient.ConnectionCallbacks() { 
          @Override 
          public void onConnected(Bundle bundle) { 
           Log.i(TAG, "Connected!!!"); 
           // Now you can make calls to the Fitness APIs. 
           new InsertAndVerifyDataTask().execute(); 


          } 

          @Override 
          public void onConnectionSuspended(int i) { 
           // If your connection to the sensor gets lost at some point, 
           // you'll be able to determine the reason and react to it here. 
           if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) { 
            Log.i(TAG, "Connection lost. Cause: Network Lost."); 
            Toast.makeText(getBaseContext(), "Connection lost. Cause: Network Lost.", Toast.LENGTH_LONG).show(); 

           } else if (i 
             == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) { 
            Log.i(TAG, 
              "Connection lost. Reason: Service Disconnected"); 
           } 
          } 
         } 
       ) 
       .enableAutoManage(this, 0, new GoogleApiClient.OnConnectionFailedListener() { 
        @Override 
        public void onConnectionFailed(ConnectionResult result) { 
         Log.i(TAG, "Google Play services connection failed. Cause: " + 
           result.toString()); 
         Toast.makeText(getBaseContext(), "Google Play services connection failed. Cause: " + 
           result.toString(), Toast.LENGTH_LONG).show(); 

        } 
       }) 
       .build(); 
    } 


} 

如果我認爲這個問題所在。

private class InsertAndVerifyDataTask extends AsyncTask<Void, Void, Void> { 
    protected Void doInBackground(Void... params) { 
     //First, create a new dataset and insertion request. 
     DataSet dataSet = insertFitnessData(); 

     // [START insert_dataset] 
     // Then, invoke the History API to insert the data and await the result, which is 
     // possible here because of the {@link AsyncTask}. Always include a timeout when calling 
     // await() to prevent hanging that can occur from the service being shutdown because 
     // of low memory or other conditions. 
     Log.i(TAG, "Inserting the dataset in the History API"); 

     com.google.android.gms.common.api.Status insertStatus = 
       Fitness.HistoryApi.insertData(mClient, dataSet) 
         .await(1, TimeUnit.MINUTES); 

     // Before querying the data, check to see if the insertion succeeded. 
     if (!insertStatus.isSuccess()) { 
      Log.i(TAG, "There was a problem inserting the dataset."); 
      return null; 
     } 

     // At this point, the data has been inserted and can be read. 
     Log.i(TAG, "Data insert was successful!"); 
     // [END insert_dataset] 

     // Begin by creating the query. 
     DataReadRequest readRequest = queryFitnessData(); 

     // [START read_dataset] 
     // Invoke the History API to fetch the data with the query and await the result of 
     // the read request. 
     DataReadResult dataReadResult = 
       Fitness.HistoryApi.readData(mClient, readRequest).await(1, TimeUnit.MINUTES); 
     // [END read_dataset] 

     // For the sake of the sample, we'll print the data so we can see what we just added. 
     // In general, logging fitness information should be avoided for privacy reasons. 
     printData(dataReadResult); 

     return null; 
    } 
} 


private DataSet insertFitnessData() { 
    Log.i(TAG, "Creating a new data insert request"); 

    // [START build_insert_data_request] 
    // Set a start and end time for our data, using a start time of 1 hour before this moment. 
    Calendar cal = Calendar.getInstance(); 
    Date now = new Date(); 
    cal.setTime(now); 
    long endTime = cal.getTimeInMillis(); 
    cal.add(Calendar.HOUR_OF_DAY, -1); 
    long startTime = cal.getTimeInMillis(); 

    // Create a data source 
    DataSource dataSource = new DataSource.Builder() 
      .setAppPackageName(this) 
      .setDataType(DataType.TYPE_STEP_COUNT_DELTA) 
      .setName(TAG + " - step count") 
      .setType(DataSource.TYPE_RAW) 
      .build(); 

    // Create a data set 
    int stepCountDelta = 1000; 
    DataSet dataSet = DataSet.create(dataSource); 
    // For each data point, specify a start time, end time, and the data value -- in this case, 
    // the number of new steps. 
    DataPoint dataPoint = dataSet.createDataPoint() 
      .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS); 

    dataPoint.getValue(Field.FIELD_STEPS).setInt(stepCountDelta); 
    dataSet.add(dataPoint); 
    // [END build_insert_data_request] 

    return dataSet; 
} 

回答

0

得到它用下面的代碼工作取得今天的步驟:

Calendar cal = Calendar.getInstance(); 
     Date now = new Date(); 
     cal.setTime(now); 
     long endTime = cal.getTimeInMillis(); 
     cal.set(Calendar.HOUR_OF_DAY, 0); 
     cal.set(Calendar.MINUTE, 00); 
     long startTime = cal.getTimeInMillis(); 


     int steps = 0; 
     DataSource ESTIMATED_STEP_DELTAS = new DataSource.Builder() 
       .setDataType(DataType.TYPE_STEP_COUNT_DELTA) 
       .setType(DataSource.TYPE_DERIVED) 
       .setStreamName("estimated_steps") 
       .setAppPackageName("com.google.android.gms").build(); 

     // fill result with just the steps from the start and end time of the present day 
     PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(mClient, DataType.AGGREGATE_STEP_COUNT_DELTA); 
     DailyTotalResult totalResult = result.await(60, TimeUnit.SECONDS); 
     if (totalResult.getStatus().isSuccess()) { 
      DataSet totalSet = totalResult.getTotal(); 
      steps = totalSet.isEmpty() ? -1 : totalSet.getDataPoints().get(0).getValue(Field.FIELD_STEPS).asInt(); 
     } 

     s = String.valueOf(steps); 

     DataReadRequest readRequest = queryFitnessData(); 

     DataReadResult dataReadResult = 
       Fitness.HistoryApi.readData(mClient, readRequest).await(1, TimeUnit.MINUTES); 
     feedItemList.clear(); 

     printData(dataReadResult); 
     return null; 
0

有時,我們也想在一個特定的時間範圍內數據的步驟,在這裏它是在這種情況下的一個原因。

裏有一些可能的原因:

1)您已經訂閱了這種類型的數據了嗎?

2)您的應用無法正常連接到Google服務。您是否從Google開發控制檯創建了OAuth客戶端ID?這是谷歌連接其GG Fit服務的強制性要求(請注意,如果您克隆另一個應用程序,在同一臺計算機上或不在同一臺計算機上,您需要重新創建另一個OAuth客戶端ID,還有一件事您需要兩個分開的帳戶,其中一個用於登錄Google開發控制檯以創建OAuth客戶端ID,一個用於在啓動您的應用程序後登錄,並且它會要求您登錄以接受其許可,......不知道爲什麼會這樣,但它會起作用)

注意:順便說一下,您可以搜索設備中的Google設置(設置 - > Google),在這裏您可以找到哪個應用連接到Google服務(包括GG Fit服務)。我建議您斷開所有連接並刪除OAuth客戶端ID,然後重新創建所有應用程序!

Mttdat。

相關問題