【问题标题】:Google fit API OAUTH IssueGoogle fit API OAUTH 问题
【发布时间】:2016-08-14 21:15:55
【问题描述】:

我正在尝试构建一个计步器应用程序,作为测试,我从 github 下载了 android fit 代码并运行了 basicsensorsAPI:

googlesamples/android-fit

为了获取步数而不是位置,我将数据类型更改为 TYPE_STEP_COUNT_CUMULATIVE 和 TYPE_DERIVED,(原件是 TYPE_LOCATION_SAMPLE 和 TYPE_RAW)。但是一旦我这样做了,OAUTH 就会停止工作,我不确定为什么这会造成问题。

这里是修改后的代码:

private void findFitnessDataSources() {
    // [START find_data_sources]
    // Note: Fitness.SensorsApi.findDataSources() requires the ACCESS_FINE_LOCATION permission.
    Fitness.SensorsApi.findDataSources(mClient, new DataSourcesRequest.Builder()
            // At least one datatype must be specified.
            .setDataTypes(DataType.TYPE_STEP_COUNT_CUMULATIVE)
                    // Can specify whether data type is raw or derived.
            .setDataSourceTypes(DataSource.TYPE_DERIVED)
            .build())
            .setResultCallback(new ResultCallback<DataSourcesResult>() {
                @Override
                public void onResult(DataSourcesResult dataSourcesResult) {
                    Log.i(TAG, "Result: " + dataSourcesResult.getStatus().toString());
                    for (DataSource dataSource : dataSourcesResult.getDataSources()) {
                        Log.i(TAG, "Data source found: " + dataSource.toString());
                        Log.i(TAG, "Data Source type: " + dataSource.getDataType().getName());

                        //Let's register a listener to receive Activity data!
                        if (dataSource.getDataType().equals(DataType.TYPE_STEP_COUNT_CUMULATIVE)
                                && mListener == null) {
                            Log.i(TAG, "Data source for LOCATION_SAMPLE found!  Registering.");
                            registerFitnessDataListener(dataSource,
                                    DataType.TYPE_STEP_COUNT_CUMULATIVE);
                        }
                    }
                }
            });
    // [END find_data_sources]
}

这是原始代码:

private void findFitnessDataSources() {
    // [START find_data_sources]
    // Note: Fitness.SensorsApi.findDataSources() requires the ACCESS_FINE_LOCATION permission.
    Fitness.SensorsApi.findDataSources(mClient, new DataSourcesRequest.Builder()
            // At least one datatype must be specified.
            .setDataTypes(DataType.TYPE_LOCATION_SAMPLE)
            // Can specify whether data type is raw or derived.
            .setDataSourceTypes(DataSource.TYPE_RAW)
            .build())
            .setResultCallback(new ResultCallback<DataSourcesResult>() {
                @Override
                public void onResult(DataSourcesResult dataSourcesResult) {
                    Log.i(TAG, "Result: " + dataSourcesResult.getStatus().toString());
                    for (DataSource dataSource : dataSourcesResult.getDataSources()) {
                        Log.i(TAG, "Data source found: " + dataSource.toString());
                        Log.i(TAG, "Data Source type: " + dataSource.getDataType().getName());

                        //Let's register a listener to receive Activity data!
                        if (dataSource.getDataType().equals(DataType.TYPE_LOCATION_SAMPLE)
                                && mListener == null) {
                            Log.i(TAG, "Data source for LOCATION_SAMPLE found!  Registering.");
                            registerFitnessDataListener(dataSource,
                                    DataType.TYPE_LOCATION_SAMPLE);
                        }
                    }
                }
            });
    // [END find_data_sources]
}

我得到这个输出:应用程序需要用户的 oAuth 同意。

【问题讨论】:

    标签: android oauth google-api google-fit google-fit-sdk


    【解决方案1】:

    我也遇到过这个问题。
    如果您遇到此问题,您需要请求许可:只需将此代码添加到您的 onResult() 方法中

    if (dataSourcesResult.getStatus().getStatusCode()==5000)
    {
        try {
            dataSourcesResult.getStatus().startResolutionForResult(SplashActivity.this,10);
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();
        }
    }
    

    onActivityResult,再次调用你的方法

    if (requestCode==10 && resultCode==RESULT_OK)
    {
        findFitnessDataSources();
    }
    

    您也可以在此处查看更多信息here。 请访问此网址。它可以向您解释有关 google fit 的所有状态代码和错误

    【讨论】:

      【解决方案2】:

      关于范围。访问此google developer page

      要为其添加数据的数据类型应在范围内。表示如果要添加

        DataType.TYPE_DISTANCE_CUMULATIVE
      

      您需要添加相关范围。这是

       .addScope(new Scope(Scopes.FITNESS_LOCATION_READ_WRITE))
      

      如果你想添加

      DataType.TYPE_STEP_COUNT_DELTA
      

      你需要添加范围

      https://www.googleapis.com/auth/fitness.activity.write

      或“FITNESS_ACTIVITY_READ_WRITE”

      【讨论】:

        【解决方案3】:

        据此Getting Started on Android

        第 3 步:获取 OAuth 2.0 客户端 ID

        如果您尚未启用 Fitness API 并获得 OAuth 2.0 客户端 ID,请立即按照获取 OAuth 2.0 客户端 ID 中的说明进行操作。

        还有,

        Authorization on Android

        在您的应用读取或写入健身数据之前,始终需要用户同意。获得授权:

        • 在 Google Developers Console 中注册您的 Android 应用程序。
        • 在连接到健身服务时指定访问范围。

        在 Google Fit 中,范围是确定应用可以访问哪些类型的健身数据以及对这些数据的访问级别的字符串。

        授权流程如下:

        • 您的应用请求与健身服务建立一个或多个访问范围的连接。
        • Google 健身会提示用户授予您的应用所需的权限。
        • 如果用户同意,您的应用可以访问范围定义的类型的健身数据。

        用户请求的具体权限取决于您的应用在连接到服务时指定的范围。

        连接到 Google Fit Platform,然后根据您在应用中使用的 Fit API 的要求检查并请求权限:

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Put application specific code here.
        
            setContentView(R.layout.activity_main);
            // This method sets up our custom logger, which will print all log messages to the device
            // screen, as well as to adb logcat.
            initializeLogging();
        
            // When permissions are revoked the app is restarted so onCreate is sufficient to check for
            // permissions core to the Activity's functionality.
            if (!checkPermissions()) {
                requestPermissions();
            }
        }
        

        创建 Google API 客户端并提供所需的回调方法:

        **
         *  Build a {@link GoogleApiClient} that will authenticate the user and allow the application
         *  to connect to Fitness APIs. The scopes included should match the scopes your app needs
         *  (see documentation for details). Authentication will occasionally fail intentionally,
         *  and in those cases, there will be a known resolution, which the OnConnectionFailedListener()
         *  can address. Examples of this include the user never having signed in before, or having
         *  multiple accounts on the device and needing to specify which account to use, etc.
         */
        private void buildFitnessClient() {
            if (mClient == null && checkPermissions()) {
                mClient = new GoogleApiClient.Builder(this)
                        .addApi(Fitness.SENSORS_API)
                        .addScope(new Scope(Scopes.FITNESS_LOCATION_READ))
                        .addConnectionCallbacks(
                                new GoogleApiClient.ConnectionCallbacks() {
                                    @Override
                                    public void onConnected(Bundle bundle) {
                                        Log.i(TAG, "Connected!!!");
                                        // Now you can make calls to the Fitness APIs.
                                        findFitnessDataSources();
                                    }
        
                                    @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 == ConnectionCallbacks.CAUSE_NETWORK_LOST) {
                                            Log.i(TAG, "Connection lost.  Cause: Network Lost.");
                                        } else if (i
                                                == 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());
                                Snackbar.make(
                                        MainActivity.this.findViewById(R.id.main_activity_view),
                                        "Exception while connecting to Google Play services: " +
                                                result.getErrorMessage(),
                                        Snackbar.LENGTH_INDEFINITE).show();
                            }
                        })
                        .build();
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2020-12-29
          • 1970-01-01
          • 1970-01-01
          • 2016-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-28
          相关资源
          最近更新 更多