Google Fit API-无法使其正常运行

时间:2016-03-18 15:19:17

标签: android google-fit

经过大量研究,主要是因为我无法理解谷歌文档,我想出了这个例子:

public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "FitActivity";
    //[START Auth_Variable_References]
    private static final int REQUEST_OAUTH = 1;
    // [END auth_variable_references]
    private GoogleApiClient mClient = null;

    int mInitialNumberOfSteps = 0;
    private TextView mStepsTextView;
    private boolean mFirstCount = true;

    // Create Builder View
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mStepsTextView = (TextView) findViewById(R.id.steps);
    }


    private void connectFitness() {
        Toast.makeText(this, "connecting", Toast.LENGTH_LONG);
        Log.i(TAG, "Connecting...");

        // Create the Google API Client
        mClient = new GoogleApiClient.Builder(this)
                // select the Fitness API
                .addApi(Fitness.SENSORS_API)
                .addApi(Fitness.RECORDING_API)
                .addApi(Fitness.SESSIONS_API)
                .addApi(Fitness.HISTORY_API)

                        // specify the scopes of access
                .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
                .addScope(new Scope(Scopes.FITNESS_LOCATION_READ))
                .addScope(new Scope(Scopes.FITNESS_BODY_READ_WRITE))
                        // provide callbacks
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        // Connect the Google API client
        mClient.connect();
    }

    // Manage OAuth authentication
    @Override
    public void onConnectionFailed(ConnectionResult result) {

        Toast.makeText(this, "failed", Toast.LENGTH_LONG);
        // Error while connecting. Try to resolve using the pending intent returned.
        if (result.getErrorCode() == ConnectionResult.SIGN_IN_REQUIRED ||
                result.getErrorCode() == FitnessStatusCodes.NEEDS_OAUTH_PERMISSIONS) {
            try {
                // Request authentication
                result.startResolutionForResult(this, REQUEST_OAUTH);
            } catch (IntentSender.SendIntentException e) {
                Log.e(TAG, "Exception connecting to the fitness service", e);
            }
        } else {
            Log.e(TAG, "Unknown connection issue. Code = " + result.getErrorCode());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_OAUTH) {
            if (resultCode == RESULT_OK) {
                // If the user authenticated, try to connect again
                mClient.connect();
            }
        }
    }

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

    @Override
    public void onConnected(Bundle bundle) {

        Log.i(TAG, "Connected!");

        Toast.makeText(this, "connected", Toast.LENGTH_LONG);
        // Now you can make calls to the Fitness APIs.
        invokeFitnessAPIs();

    }

    private void invokeFitnessAPIs() {

        getStepsToday();


    }

    private void getStepsToday() {
        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, 0);
        cal.set(Calendar.SECOND, 0);
        long startTime = cal.getTimeInMillis();

        final DataReadRequest readRequest = new DataReadRequest.Builder()
                .read(DataType.TYPE_STEP_COUNT_DELTA)
                .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
                .build();

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

        DataSet stepData = dataReadResult.getDataSet(DataType.TYPE_STEP_COUNT_DELTA);

        int totalSteps = 0;

        for (DataPoint dp : stepData.getDataPoints()) {
            for(Field field : dp.getDataType().getFields()) {
                int steps = dp.getValue(field).asInt();

                totalSteps += steps;

            }
        }

        TextView steps = (TextView)findViewById(R.id.steps);
        steps.setText(totalSteps);
    }

    // Update the Text Viewer with Counter of Steps..
    private void updateTextViewWithStepCounter(final int numberOfSteps) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getBaseContext(), "On Datapoint!", Toast.LENGTH_SHORT);

                if(mFirstCount && (numberOfSteps != 0)) {
                    mInitialNumberOfSteps = numberOfSteps;
                    mFirstCount = false;
                }
                if(mStepsTextView != null){
                    mStepsTextView.setText(String.valueOf(numberOfSteps - mInitialNumberOfSteps));
                }
            }
        });
    }

    //Start
    @Override
    protected void onStart() {
        super.onStart();
        mFirstCount = true;
        mInitialNumberOfSteps = 0;
        if (mClient == null || !mClient.isConnected()) {
            connectFitness();
        }
    }
    //Stop
    @Override
    protected void onStop() {
        super.onStop();
        if(mClient.isConnected() || mClient.isConnecting()) mClient.disconnect();
        mInitialNumberOfSteps = 0;
        mFirstCount = true;
    }

logs我注意到此代码不会调用任何Google fitmethods。有人能帮助我吗?另外我在哪里放置我的OAuth 2.0信息?我真的迷失了,甚至对Google API本身的一些解释也会有所帮助。

1 个答案:

答案 0 :(得分:0)

经过大量研究后,我想出了最近的tutoriallibrary