Android Google Fit example is not working

╄→尐↘猪︶ㄣ 提交于 2019-12-23 03:41:13

问题


I have problems to get the example apps for Google Fit running provided by Google.

I figured out so far, that the resultCode I get in onActivityResult is 0 after I selected an Account.

The example app I use at the moment is BasicRecordingApi, which can be found here. But I've tried the others too.

I created an API key for the app and I enabled Google Fit API already.

Nothing helps.

Any ideas?


回答1:


Getting Started on Android

This explains how to start developing with Google Fit on Android. Google Fit is part of Google Play services.

Step 1: Get Google Play services

Google Fit is available on Android devices with Google Play services 7.0 or higher. Devices running Android 2.3 or higher that have the Google Play Store app automatically receive updates to Google Play services.

To check which version of Google Play services is installed on your device, go to Settings > Apps > Google Play services.

Ensure that you have the latest client library for Google Play services on your development host:

1.Open the Android SDK Manager. 2.Under Extras, find Google Play services and Google Repository. 3.If the status for these packages is different than Installed, select them both and click Install Packages.

Step 2: Get a Google Account To use the Google Fit APIs, you need a Google Account.

Step 3: Enable the Fitness API create a project at google console

1.Go to the Google Developers Console. 2.Click Create Project. 3.In the Project Name field, type a name for your project and click Create.

Activate the Fitness API 1.Go to the Google Developers Console. 2.In the left sidebar, click APIs and Auth. 3.Find the Fitness API and set its status to ON.

Create a new client ID

1.Go to the Google Developers Console. 2.In the left sidebar, click Credentials. 3.Click Create a new Client ID. The Create Client ID dialog box appears. 4.Under Application Type, select Installed application. 5.Under Installed Application Type, select Android. 6.In the Package Name field, enter the package name of your Android app. 7.In the Signing Certificate Fingerprint (SHA1) field, enter the SHA1 fingerprint of your certificate. 8.Click Create Client ID.

Step 4: Configure your project

In the IDE, open the build.gradle file for your module and add the Google Play services client library as a dependency:

 apply plugin: 'com.android.application'
    ...

    dependencies {
        compile 'com.google.android.gms:play-services-fitness:8.3.0'
    }

Step 5: Connect to the fitness service

Getting Started on Android

This document explains how to start developing with Google Fit on Android. Google Fit is part of Google Play services.

Step 1: Get Google Play services

Google Fit is available on Android devices with Google Play services 7.0 or higher. Devices running Android 2.3 or higher that have the Google Play Store app automatically receive updates to Google Play services.

To check which version of Google Play services is installed on your device, go to Settings > Apps > Google Play services.

Ensure that you have the latest client library for Google Play services on your development host:

Open the Android SDK Manager. Under Extras, find Google Play services and Google Repository. If the status for these packages is different than Installed, select them both and click Install Packages. Step 2: Get a Google Account

To use the Google Fit APIs, you need a Google Account. If you already have an account, then you're all set. You may also want a separate Google Account for testing purposes.

Step 3: Enable the Fitness API

To authenticate and communicate with Google Fit, you must create a project in the Google Developers Console, activate the Fitness API, create an OAuth 2.0 client ID, and register the public certificate from your app's signed APK.

Create a project

Note: Use the same project for the Android and REST versions of your app. Go to the Google Developers Console. Click Create Project. In the Project Name field, type a name for your project and click Create. Activate the Fitness API

Go to the Google Developers Console. In the left sidebar, click APIs and Auth. Find the Fitness API and set its status to ON. The Fitness API now appears at the top of the API list.

Obtain the SHA1 fingerprint of your certificate

To create a new client ID for your Android app, you need the SHA1 fingerprint of the certificate you use to sign your APK. To obtain this fingerprint:

Find the location of your keystore. In a terminal, run the keytool utility from the JDK. For example, if you are using the debug keystore: $ keytool -exportcert -alias \ androiddebugkey -keystore \ ~/.android/debug.keystore -list -v Note: On Mac OS and Linux, the debug keystore is typically located at ~/.android/debug.keystore. On Windows, it is typically located at %USERPROFILE%.android\debug.keystore.

The output of the keytool command contains the SHA1 fingerprint for the certicate.

Figure 1: The Create Client ID dialog box. Create a new client ID

Go to the Google Developers Console. In the left sidebar, click Credentials. Click Create a new Client ID. The Create Client ID dialog box appears. Under Application Type, select Installed application. Under Installed Application Type, select Android. In the Package Name field, enter the package name of your Android app. In the Signing Certificate Fingerprint (SHA1) field, enter the SHA1 fingerprint of your certificate. Click Create Client ID. Step 4: Configure your project

Android Studio makes it easy to create a project for Google Fit. Follow the steps described in Creating a Project.

In the IDE, open the build.gradle file for your module and add the Google Play services client library as a dependency:

apply plugin: 'com.android.application'
...

dependencies {
    compile 'com.google.android.gms:play-services-fitness:8.3.0'
}

Step 5: Connect to the fitness service

Before you can invoke methods from the Google Fit APIs, you have to connect to the appropriate fitness service or services, which are part of Google Play services. The following APIs are available to you:

1.Fitness.SENSORS_API
2.Fitness.RECORDING_API
3.Fitness.HISTORY_API
4.Fitness.SESSIONS_API
5.Fitness.BLE_API
6.Fitness.CONFIG_API

Create the API client as follows:

1.Define variables in your activity to help you track the connection status:

private static final int REQUEST_OAUTH = 1;

/**
 *  Track whether an authorization activity is stacking over the current activity, i.e. when
 *  a known auth error is being resolved, such as showing the account chooser or presenting a
 *  consent dialog. This avoids common duplications as might happen on screen rotations, etc.
 */
private static final String AUTH_PENDING = "auth_state_pending";
private boolean authInProgress = false;

private GoogleApiClient mClient = null;

2.Determine whether the authentication is in progress in the onCreate method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Put application specific code here.

    if (savedInstanceState != null) {
        authInProgress = savedInstanceState.getBoolean(AUTH_PENDING);
    }

    buildFitnessClient();
}

**3.Create the Google API client and provide the required callback methods:*

/**
 *  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() {
    // Create the Google API Client
    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.
                            // Put application specific code here.
                        }

                        @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");
                            }
                        }
                    }
            )
            .addOnConnectionFailedListener(
                    new GoogleApiClient.OnConnectionFailedListener() {
                        // Called whenever the API client fails to connect.
                        @Override
                        public void onConnectionFailed(ConnectionResult result) {
                            Log.i(TAG, "Connection failed. Cause: " + result.toString());
                            if (!result.hasResolution()) {
                                // Show the localized error dialog
                                GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
                                        MainActivity.this, 0).show();
                                return;
                            }
                            // The failure has a resolution. Resolve it.
                            // Called typically when the app is not yet authorized, and an
                            // authorization dialog is displayed to the user.
                            if (!authInProgress) {
                                try {
                                    Log.i(TAG, "Attempting to resolve failed connection");
                                    authInProgress = true;
                                    result.startResolutionForResult(MainActivity.this,
                                            REQUEST_OAUTH);
                                } catch (IntentSender.SendIntentException e) {
                                    Log.e(TAG,
                                            "Exception while starting resolution activity", e);
                                }
                            }
                        }
                    }
            )
            .build();
}

4.Manage the connection lifecycle of your client inside your activity:

@Override
protected void onStart() {
    super.onStart();
    // Connect to the Fitness API
    Log.i(TAG, "Connecting...");
    mClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    if (mClient.isConnected()) {
        mClient.disconnect();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_OAUTH) {
        authInProgress = false;
        if (resultCode == RESULT_OK) {
            // Make sure the app is not already connected or attempting to connect
            if (!mClient.isConnecting() && !mClient.isConnected()) {
                mClient.connect();
            }
        }
    }
}

@Override
   protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
  }


来源:https://stackoverflow.com/questions/34017544/android-google-fit-example-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!