【问题标题】:How to find steps with Google Fit API for Android?如何使用适用于 Android 的 Google Fit API 查找步骤?
【发布时间】:2016-01-20 14:05:56
【问题描述】:

我已经对此进行了几天的研究。我只需要在我的应用程序中使用一个简单的 TextView 区域来显示今天的步骤。

我已经设法让身份验证与下面的代码一起工作。它弹出请求许可,并认为我选择了正确的。

但我不知道如何简单地获取步数信息。我希望这只是几行代码。任何帮助,将不胜感激。谢谢

编辑 1:我只需要获取步数。我可以弄清楚以后如何显示它。我也有 Toasts 来帮助我弄清楚发生了什么。

private void buildFitnessClient() {
    if (mClient == null) {
        mClient = new GoogleApiClient.Builder(this)
                .addApi(Fitness.SENSORS_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.
                                Toast.makeText(getBaseContext(), "Connected!", Toast.LENGTH_LONG).show();


                            }

                            @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();
    }
}

【问题讨论】:

标签: java android api google-fit


【解决方案1】:

根据新的更新,不推荐使用 GoogleApiClient。以及 HistoryApi 也已被弃用。所以首先必须使用 GoogleSignInAccount 而不是 GoogleApiClient 并且还要使用 Google Fit 的 HistoryClient 而不是 HistoryApi。

设置健身选项

 val fitnessOptions: GoogleSignInOptionsExtension = FitnessOptions.builder()
        .addDataType(TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ).build()

设置 Google 登录选项

val googleSignInOptions =
        GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .addExtension(fitnessOptions).requestEmail().build()
    val googleSignInClient = GoogleSignIn.getClient(requireActivity(), googleSignInOptions)
    val signIntent = googleSignInClient.signInIntent
    startActivityForResult(signIntent, 0)

获取帐户

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
        val task = GoogleSignIn.getSignedInAccountFromIntent(data)
        val account = task.getResult(ApiException::class.java)
        if (account != null) {
            getGoogleFitData(account)
        }
    }
}

现在获取步数数据

val response: Task<DataReadResponse> =
            Fitness.getHistoryClient(mContext, mSignInAccount)
                .readData(
                    DataReadRequest.Builder()
                        .read(TYPE_STEP_COUNT_DELTA)
                        .setTimeRange(
                            startTime,
                            endTime,
                            TimeUnit.MILLISECONDS
                        )
                        .build()
                )

        val readDataResult: DataReadResponse? = Tasks.await(response)
        val dataSet: DataSet = readDataResult!!.getDataSet(TYPE_STEP_COUNT_DELTA)

        var total = 0
        if (!dataSet.isEmpty) {
            val dataPoints = dataSet.dataPoints
            if (dataPoints.size > 0) {
                for (i in 0 until dataPoints.size) {
                    total += dataSet.dataPoints[i].getValue(Field.FIELD_STEPS).asInt()
                }
                Log.e(TAG, "Total Steps : $total")
            }
        }
  • 这里的 startTime 和 endTime 是任何日期和时间的计时器。

谢谢。

【讨论】:

  • 是的,当然。我已经更新了我的答案,看看你肯定会找到一些解决方案。谢谢
  • 谢谢伙计。你能检查一下,看看你是否有任何线索stackoverflow.com/questions/65933509/…
  • 我已经回复了你的问题,请查收。
  • 谢谢兄弟!!我已在我的 google fit 应用程序中手动输入数据。但我的历史 API 数据点值似乎返回空。即使我添加任何数据,它也不会反映在 google fit 应用程序中。我缺少一些同步选项吗??
【解决方案2】:

查看来自 Google 的 official documentation,了解如何从 Fit 读取数据:

// Setting a start and end date using a range of 1 week before this moment.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.WEEK_OF_YEAR, -1);
long startTime = cal.getTimeInMillis();

java.text.DateFormat dateFormat = getDateInstance();
Log.i(TAG, "Range Start: " + dateFormat.format(startTime));
Log.i(TAG, "Range End: " + dateFormat.format(endTime));

DataReadRequest readRequest = new DataReadRequest.Builder()
        // The data request can specify multiple data types to return, effectively
        // combining multiple data queries into one call.
        // In this example, it's very unlikely that the request is for several hundred
        // datapoints each consisting of a few steps and a timestamp.  The more likely
        // scenario is wanting to see how many steps were walked per day, for 7 days.
        .aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
        // Analogous to a "Group By" in SQL, defines how data should be aggregated.
        // bucketByTime allows for a time span, whereas bucketBySession would allow
        // bucketing by "sessions", which would need to be defined in code.
        .bucketByTime(1, TimeUnit.DAYS)
        .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
        .build();

GitHub 上的历史 API 示例应用:

查看 GitHub here 上的示例项目。

包含所需代码的MainActivity.java(在上述示例项目中)的直接链接:Link

【讨论】:

  • 好吧,这很累,它不会带回任何错误。在此之后,我使用此代码将其传递给结果。 DataReadResult dataReadResult = Fitness.HistoryApi.readData(mClient, readRequest).await(1, TimeUnit.MINUTES);不过,我仍然无法将其传递给 TextView 甚至是 toast。
  • 数据给你了吗?
  • 我不知道如何检查。如何读取数据结果。我试过这个但没有运气,因为我无法将数据集传递给它。 developers.google.com/fit/android/history#read_daily_total_data
  • 在答案中添加了示例项目的链接。检查
猜你喜欢
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多