Google适合API OAUTH问题

时间:2016-04-21 15:02:32

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

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

googlesamples/android-fit

为了获得stepcount而不是location,我将数据类型更改为 TYPE_STEP_COUNT_CUMULATIVE和TYPE_DERIVED ,(orignials为 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同意。

3 个答案:

答案 0 :(得分:3)

我也遇到过这个问题 如果您遇到此问题,则需要获得权限:只需在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健身的所有状态代码和错误

答案 1 :(得分:0)

根据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健身中,范围是字符串,用于确定应用可以访问哪种健身数据以及对此数据的访问级别。

     

授权流程如下:

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

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

连接到Google健身平台,然后根据您在应用中使用的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();
    }
}

答案 2 :(得分:0)

关于范围。访问此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

或&#34; FITNESS_ACTIVITY_READ_WRITE&#34;