21

私は現在、Google Fit API を使用しようとしています。これは API を使用する初めてのアプリであり、主に Google のドキュメントに従っています。

以下は、問題があると思われるコードです

私が抱えている問題は、歩数カウンターを更新していないように見えることです。

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);
            mStepsTextView = (TextView) findViewById(R.id.textview_number_of_steps);
        }


        private void connectFitness() {
            Log.i(TAG, "Connecting...");

            // Create the Google API Client
            mClient = new GoogleApiClient.Builder(this)
                    // select the Fitness API
                    .addApi(Fitness.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) {

            // 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.
            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!");

            // Now you can make calls to the Fitness APIs.
            invokeFitnessAPIs();

        }

        private void invokeFitnessAPIs() {

            // Create a listener object to be called when new data is available
            OnDataPointListener listener = new OnDataPointListener() {
                @Override
                public void onDataPoint(DataPoint dataPoint) {

                    for (Field field : dataPoint.getDataType().getFields()) {
                        Value val = dataPoint.getValue(field);
                        updateTextViewWithStepCounter(val.asInt());
                    }
                }
            };

            //Specify what data sources to return
            DataSourcesRequest req = new DataSourcesRequest.Builder()
                    .setDataSourceTypes(DataSource.TYPE_DERIVED)
                    .setDataTypes(DataType.TYPE_STEP_COUNT_DELTA)
                    .build();

            //  Invoke the Sensors API with:
            // - The Google API client object
            // - The data sources request object
            PendingResult<DataSourcesResult> pendingResult =
                    Fitness.SensorsApi.findDataSources(mClient, req);

            //  Build a sensor registration request object
            SensorRequest sensorRequest = new SensorRequest.Builder()
                    .setDataType(DataType.TYPE_STEP_COUNT_CUMULATIVE)
                    .setSamplingRate(1, TimeUnit.SECONDS)
                    .build();

            //  Invoke the Sensors API with:
            // - The Google API client object
            // - The sensor registration request object
            // - The listener object
            PendingResult<Status> regResult =
              Fitness.SensorsApi.add(mClient,
                      new SensorRequest.Builder()
                      .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
                      .build(),
                      listener);


            // 4. Check the result asynchronously
            regResult.setResultCallback(new ResultCallback<Status>()
            {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        Log.d(TAG, "listener registered");
                        // listener registered
                    } else {
                        Log.d(TAG, "listener not registered");
                        // listener not registered
                    }
                }
            });
        }

        // 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;
        }

    }
4

4 に答える 4

1

OrangeGangster のStepSensorライブラリを試すことができます。

Serviceこれには、Android 4.4 で導入された からデータを収集できるカスタムが含まれていますSensor.TYPE_STEP_COUNTER(このハードウェア機能をサポートするデバイスでのみ使用できます)。

于 2015-07-27T11:50:52.957 に答える
1

このコードは私のために働きます!

クライアントの構築:

mClient = new GoogleApiClient.Builder(this)
            .addApi(Fitness.SENSORS_API)
            .addScope(new Scope(Scopes.FITNESS_BODY_READ_WRITE))
            .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

センサー API の呼び出し:

private void invokeSensorsAPI() {
    Fitness.SensorsApi.add(
            mClient,
            new SensorRequest.Builder()
                    .setDataType(DataType.TYPE_STEP_COUNT_DELTA) 
                    .setSamplingRate(1, TimeUnit.SECONDS)
                    .build(),
            this)
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        Log.i(TAG, "Sensor Listener registered!");
                    } else {
                        Log.i(TAG, "Sensor Listener not registered.");
                    }
                }
            });
}

データの受信:

@Override
public void onDataPoint(DataPoint dataPoint) { 
  for (Field field : dataPoint.getDataType().getFields()) {
        Value val = dataPoint.getValue(field);
        Log.i(TAG, "Detected DataPoint field: " + field.getName());
        Log.i(TAG, "Detected DataPoint value: " + val);
        final int value = val.asInt();

        if (field.getName().compareToIgnoreCase("steps") == 0) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText("Value" + value)
                    }
                });
        }

    }
}

役立つことを願っています

于 2015-08-01T22:28:28.200 に答える
0

私はあなたがここで間違いを犯していると思います

if (resultCode == RESULT_OK) {
    // If the user authenticated, try to connect again
    mClient.connect()
}

代わりにそうあるべきです

if (resultCode != RESULT_OK) {
    // If the user is not authenticated, try to connect again/ resultcode = RESULT_CANCEL
    mClient.connect()
} else {
    onConnected(null);
}

あなたのコードでは、接続が成功した後に googleapiclient に再接続しているため、invokeFitnessApis が呼び出されることはありません。

于 2016-08-08T05:00:51.797 に答える