com.google.android.gms.fitness.Fitness Java Examples

The following examples show how to use com.google.android.gms.fitness.Fitness. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Manager.java    From react-native-fitness with MIT License 9 votes vote down vote up
public void subscribeToSteps(Context context, final Promise promise){
    final GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(context);
    if(account == null){
        promise.resolve(false);
        return;
    }
    Fitness.getRecordingClient(context, account)
            .subscribe(DataType.TYPE_STEP_COUNT_DELTA)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    promise.resolve(true);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    promise.resolve(false);
                }
            });
}
 
Example #2
Source File: GoogleFit.java    From cordova-plugin-googlefit with MIT License 6 votes vote down vote up
@Override
public void run() {
    if (!mClient.isConnected()) {
        mClient.connect();
    }

    Fitness.HistoryApi.readData(mClient, request)
        .setResultCallback(new ResultCallback<DataReadResult>() {
            @Override
            public void onResult(DataReadResult dataReadResult) {

                if (dataReadResult.getBuckets().size() > 0) {
                    callbackContext.success(convertBucketsToJson(dataReadResult.getBuckets())); // Thread-safe.
                } else if (dataReadResult.getDataSets().size() > 0) {
                    callbackContext.success(convertDatasetsToJson(dataReadResult.getDataSets())); // Thread-safe.
                } else {
                    callbackContext.error("No dataset and no buckets."); // Thread-safe.
                }
            }
        });
}
 
Example #3
Source File: HydrationHistory.java    From react-native-google-fit with MIT License 6 votes vote down vote up
public ReadableArray getHistory(long startTime, long endTime) {
  DateFormat dateFormat = DateFormat.getDateInstance();

  DataReadRequest readRequest = new DataReadRequest.Builder()
    .read(this.dataType)
    .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS).build();

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

  WritableArray map = Arguments.createArray();

  if (dataReadResult.getDataSets().size() > 0) {
    for (DataSet dataSet : dataReadResult.getDataSets()) {
      processDataSet(dataSet, map);
    }
  }

  return map;
}
 
Example #4
Source File: BodyHistory.java    From react-native-google-fit with MIT License 6 votes vote down vote up
protected Void doInBackground(Void... params) {
    // Create a new dataset and insertion request.
    DataSet dataSet = this.Dataset;

    // [START insert_dataset]
    // Then, invoke the History API to insert the data and await the result, which is
    // possible here because of the {@link AsyncTask}. Always include a timeout when calling
    // await() to prevent hanging that can occur from the service being shutdown because
    // of low memory or other conditions.
    //Log.i(TAG, "Inserting the dataset in the History API.");
    com.google.android.gms.common.api.Status insertStatus =
            Fitness.HistoryApi.insertData(googleFitManager.getGoogleApiClient(), dataSet)
                    .await(1, TimeUnit.MINUTES);

    // Before querying the data, check to see if the insertion succeeded.
    if (!insertStatus.isSuccess()) {
        //Log.i(TAG, "There was a problem inserting the dataset.");
        return null;
    }

    //Log.i(TAG, "Data insert was successful!");

    return null;
}
 
Example #5
Source File: HeartrateHistory.java    From react-native-google-fit with MIT License 6 votes vote down vote up
protected Void doInBackground(Void... params) {
    // Create a new dataset and insertion request.
    DataSet dataSet = this.Dataset;

    // [START insert_dataset]
    // Then, invoke the History API to insert the data and await the result, which is
    // possible here because of the {@link AsyncTask}. Always include a timeout when calling
    // await() to prevent hanging that can occur from the service being shutdown because
    // of low memory or other conditions.
    //Log.i(TAG, "Inserting the dataset in the History API.");
    com.google.android.gms.common.api.Status insertStatus =
            Fitness.HistoryApi.insertData(googleFitManager.getGoogleApiClient(), dataSet)
                    .await(1, TimeUnit.MINUTES);

    // Before querying the data, check to see if the insertion succeeded.
    if (!insertStatus.isSuccess()) {
        //Log.i(TAG, "There was a problem inserting the dataset.");
        return null;
    }

    //Log.i(TAG, "Data insert was successful!");

    return null;
}
 
Example #6
Source File: GoogleFitModule.java    From react-native-google-fitness with MIT License 6 votes vote down vote up
@ReactMethod
public void disableFit(Promise promise) {
    try {
        Fitness
                .getConfigClient(mReactContext, getLastSignedInAccountSafely())
                .disableFit()
                .continueWithTask(new Continuation<Void, Task<Void>>() {
                    @Override
                    public Task<Void> then(@NonNull Task<Void> task) throws Exception {
                        GoogleSignInOptions options = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).build();
                        return GoogleSignIn
                                .getClient(mReactContext, options)
                                .signOut();
                    }
                })
                .addOnFailureListener(new SimpleFailureListener(promise))
                .addOnSuccessListener(new SimpleSuccessListener(promise));
    } catch (Exception e) {
        promise.reject(e);
    }
}
 
Example #7
Source File: Manager.java    From react-native-fitness with MIT License 6 votes vote down vote up
public void subscribeToActivity(Context context, final Promise promise){
    final GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(context);
    if(account == null){
        promise.resolve(false);
        return;
    }
    Fitness.getRecordingClient(context, account)
            .subscribe(DataType.TYPE_ACTIVITY_SAMPLES)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    promise.resolve(true);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    promise.resolve(false);
                }
            });

}
 
Example #8
Source File: CalorieHistory.java    From react-native-google-fit with MIT License 6 votes vote down vote up
protected Void doInBackground(Void... params) {
    // Create a new dataset and insertion request.
    DataSet dataSet = this.FoodDataset;

    // [START insert_dataset]
    // Then, invoke the History API to insert the data and await the result, which is
    // possible here because of the {@link AsyncTask}. Always include a timeout when calling
    // await() to prevent hanging that can occur from the service being shutdown because
    // of low memory or other conditions.
    //Log.i(TAG, "Inserting the dataset in the History API.");
    com.google.android.gms.common.api.Status insertStatus =
            Fitness.HistoryApi.insertData(googleFitManager.getGoogleApiClient(), dataSet)
                    .await(1, TimeUnit.MINUTES);

    // Before querying the data, check to see if the insertion succeeded.
    if (!insertStatus.isSuccess()) {
        //Log.i(TAG, "There was a problem inserting the dataset.");
        return null;
    }

    //Log.i(TAG, "Data insert was successful!");

    return null;
}
 
Example #9
Source File: StepCounter.java    From react-native-google-fit with MIT License 6 votes vote down vote up
public void findFitnessDataSources() {

        DataSourcesRequest dataSourceRequest = new DataSourcesRequest.Builder()
                .setDataTypes(DataType.TYPE_STEP_COUNT_DELTA, DataType.TYPE_STEP_COUNT_CUMULATIVE)
                .setDataSourceTypes( DataSource.TYPE_DERIVED)
                .build();

        ResultCallback<DataSourcesResult> dataSourcesResultCallback = new ResultCallback<DataSourcesResult>() {
            @Override
            public void onResult(DataSourcesResult dataSourcesResult) {
                for (DataSource dataSource : dataSourcesResult.getDataSources()) {
                    DataType type = dataSource.getDataType();

                    if (DataType.TYPE_STEP_COUNT_DELTA.equals(type)
                            || DataType.TYPE_STEP_COUNT_CUMULATIVE.equals(type)) {
                        Log.i(TAG, "Register Fitness Listener: " + type);
                        registerFitnessDataListener(dataSource, type);//DataType.TYPE_STEP_COUNT_DELTA);
                    }
                }
            }
        };

        Fitness.SensorsApi.findDataSources(googleFitManager.getGoogleApiClient(), dataSourceRequest)
                .setResultCallback(dataSourcesResultCallback);
    }
 
Example #10
Source File: StepCounter.java    From react-native-google-fit with MIT License 6 votes vote down vote up
private void registerFitnessDataListener(DataSource dataSource, DataType dataType) {

        SensorRequest request = new SensorRequest.Builder()
                .setDataSource(dataSource)
                .setDataType(dataType)
                .setSamplingRate(3, TimeUnit.SECONDS)
                .build();

        Fitness.SensorsApi.add(googleFitManager.getGoogleApiClient(), request, this)
                .setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        if (status.isSuccess()) {
                            Log.i(TAG, "SensorApi successfully added");
                        }
                    }
                });
    }
 
Example #11
Source File: GoogleApiClientWrapper.java    From android-play-games-in-motion with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a GoogleApiClient that connects to the Fitness Api.
 * @param activity The activity through which authorization UI will be launched.
 */
public void buildGoogleApiClient(Activity activity) {
    if (mGoogleApiClient != null) {
        return;
    }
    Utils.logDebug(TAG, "Building the Google Api Client.");

    mActivity = activity;

    // Create the Google API Client.
    mGoogleApiClient = new GoogleApiClient.Builder(activity, this, this)
            .addApi(Fitness.API)                    // Fitness API
            .addScope(Fitness.SCOPE_ACTIVITY_READ)  // Fitness Scopes
            .addScope(Fitness.SCOPE_LOCATION_READ)
            .addApi(Games.API)                      // Games API
            .addScope(Games.SCOPE_GAMES)            // Games Scope
            .build();
}
 
Example #12
Source File: GoogleFit.java    From cordova-plugin-googlefit with MIT License 6 votes vote down vote up
@Override
public void run() {
    if (!mClient.isConnected()) {
        mClient.connect();
    }

    Fitness.HistoryApi.readData(mClient, request)
        .setResultCallback(new ResultCallback<DataReadResult>() {
            @Override
            public void onResult(DataReadResult dataReadResult) {

                if (dataReadResult.getBuckets().size() > 0) {
                    callbackContext.success(convertBucketsToJson(dataReadResult.getBuckets())); // Thread-safe.
                } else if (dataReadResult.getDataSets().size() > 0) {
                    callbackContext.success(convertDatasetsToJson(dataReadResult.getDataSets())); // Thread-safe.
                } else {
                    callbackContext.error("No dataset and no buckets."); // Thread-safe.
                }
            }
        });
}
 
Example #13
Source File: GoogleApiClientWrapper.java    From android-play-games-in-motion with Apache License 2.0 6 votes vote down vote up
/**
 * Starts a new session for Fit data. This will take care of registering all the sensors,
 * recording the sensor data, and registering the data set as a session to Google Fit.
 * @param dataTypeSettings Types of data to listen to, in an array.
 * @param sessionDescription The description of the session.
 * @param listener The OnDataPointListener to receive sensor events.
 */
public void startFitDataSession(FitDataTypeSetting[] dataTypeSettings,
                                String sessionDescription, OnDataPointListener listener) {
    for (FitDataTypeSetting dataTypeSetting : dataTypeSettings) {
        registerFitDataListener(dataTypeSetting, listener);
        startRecordingFitData(dataTypeSetting);
    }

    Session session = new Session.Builder()
            .setName(SESSION_NAME)
            .setDescription(sessionDescription)
            .setActivity(FitnessActivities.RUNNING_JOGGING)
            .setStartTime(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
            .build();

    PendingResult<Status> pendingResult =
            Fitness.SessionsApi.startSession(mGoogleApiClient, session);
    pendingResult.setResultCallback(new FitResultCallback<Status>(
            this, FitResultCallback.RegisterType.SESSION, null /* dataType */,
            true /* subscribe */));
}
 
Example #14
Source File: GoogleApiClientWrapper.java    From android-play-games-in-motion with Apache License 2.0 6 votes vote down vote up
/**
 * Add SensorsApi listener for real-time display of sensor data. Can be called repeatedly on
 * multiple data types.
 * @param dataTypeSetting Type of data to listen to.
 * @param listener Listener for callbacks from SensorsApi.
 */
private void registerFitDataListener(
        FitDataTypeSetting dataTypeSetting, OnDataPointListener listener) {
    sensorsAwaitingRegistration.add(dataTypeSetting);
    Fitness.SensorsApi.add(
            mGoogleApiClient,
            new SensorRequest.Builder()
                    .setDataType(dataTypeSetting.getDataType())
                    .setSamplingRate(dataTypeSetting.getSamplingRateSeconds(), TimeUnit.SECONDS)
                    .setAccuracyMode(dataTypeSetting.getAccuracyMode())
                    .build(),
            listener)
            .setResultCallback(new FitResultCallback<Status>(
                    this, FitResultCallback.RegisterType.SENSORS, dataTypeSetting.getDataType(),
                    true));
}
 
Example #15
Source File: DataManager.java    From GoogleFitExample with Apache License 2.0 6 votes vote down vote up
/**
 *  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(final Context context) {
    if (context != null) {
        Log.i(TAG, "Creating the Google API Client with context: " + context.getClass().getName());
        // Create the Google API Client
        mClient = new GoogleApiClient.Builder(context)
                .addApiIfAvailable(Fitness.SENSORS_API)
                .addApi(Fitness.SESSIONS_API)
                .addApi(Fitness.HISTORY_API)
                .addApi(Fitness.RECORDING_API)
                //.addApi(LocationServices.API)
                .addScope(new Scope(Scopes.PROFILE))
                //.addScope(new Scope(Scopes.FITNESS_LOCATION_READ_WRITE))
                .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

}
 
Example #16
Source File: DataManager.java    From GoogleFitExample with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch a list of all active subscriptions and log it. Since the logger for this sample
 * also prints to the screen, we can see what is happening in this way.
 */
private void dumpSubscriptionsList() {
    Log.i(TAG, "Dumping subscriptions.");
    // [START list_current_subscriptions]
    Fitness.RecordingApi.listSubscriptions(mClient)
            // Create the callback to retrieve the list of subscriptions asynchronously.
            .setResultCallback(new ResultCallback<ListSubscriptionsResult>() {
                @Override
                public void onResult(ListSubscriptionsResult listSubscriptionsResult) {
                    for (Subscription sc : listSubscriptionsResult.getSubscriptions()) {
                        DataType dt = sc.getDataType();
                        Log.i(TAG, "Active subscription for data type: " + dt.getName());
                    }
                }
            });
    // [END list_current_subscriptions]
}
 
Example #17
Source File: GoogleFit.java    From OpenFit with MIT License 6 votes vote down vote up
public void disconnectGoogleFit() {
    if(mClient.isConnected()) {
        Log.d(LOG_TAG, "Disconnecting to GoogleFit");
        PendingResult<Status> pendingResult = Fitness.ConfigApi.disableFit(mClient);

        pendingResult.setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                if(status.isSuccess()) {
                    //GFIT_CONNECTED = false;
                    Log.d(LOG_TAG, "Google Fit disabled");
                    Intent msg = new Intent(OpenFitIntent.INTENT_GOOGLE_FIT);
                    msg.putExtra(OpenFitIntent.INTENT_EXTRA_MSG, OpenFitIntent.INTENT_GOOGLE_FIT);
                    msg.putExtra(OpenFitIntent.INTENT_EXTRA_DATA, false);
                    //getActivity().sendBroadcast(msg);

                    mClient.disconnect();
                } else {
                    Log.e(LOG_TAG, "Google Fit wasn't disabled " + status);
                }
            }
        });
    }
}
 
Example #18
Source File: GoogleApiClientWrapper.java    From android-play-games-in-motion with Apache License 2.0 6 votes vote down vote up
/**
 * Ends the session for Fit data. This will take care of un-registering all the sensors,
 * stop recording the sensor data, and stop recording the data set as a session to Google Fit.
 * @param dataTypeSettings Types of data to listen to, in an array.
 * @param listener The OnDataPointListener to receive sensor events.
 */
public void endFitDataSession(
        FitDataTypeSetting[] dataTypeSettings, OnDataPointListener listener) {
    if (mGoogleApiClient.isConnected()) {
        PendingResult<SessionStopResult> pendingResult =
                Fitness.SessionsApi.stopSession(mGoogleApiClient, null);
        pendingResult.setResultCallback(new FitResultCallback<SessionStopResult>(
                this, FitResultCallback.RegisterType.SESSION, null /* dataType */,
                false /* subscribe */));

        for (FitDataTypeSetting dataTypeSetting : dataTypeSettings) {
            stopRecordingFitData(dataTypeSetting);
            unregisterFitDataListener(listener);
        }
    }
}
 
Example #19
Source File: OpenFitActivity.java    From OpenFit with MIT License 6 votes vote down vote up
public void disconnectGoogleFit() {
    if(mClient.isConnected()) {
        Log.d(LOG_TAG, "Disconnecting to GoogleFit");
        PendingResult<Status> pendingResult = Fitness.ConfigApi.disableFit(mClient);

        pendingResult.setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                if(status.isSuccess()) {
                    GFIT_CONNECTED = false;
                    Log.d(LOG_TAG, "Google Fit disabled");
                    Intent msg = new Intent(OpenFitIntent.INTENT_GOOGLE_FIT);
                    msg.putExtra(OpenFitIntent.INTENT_EXTRA_MSG, OpenFitIntent.INTENT_GOOGLE_FIT);
                    msg.putExtra(OpenFitIntent.INTENT_EXTRA_DATA, false);
                    getActivity().sendBroadcast(msg);

                    mClient.disconnect();
                }
                else {
                    Log.e(LOG_TAG, "Google Fit wasn't disabled " + status);
                }
            }
        });
    }
}
 
Example #20
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

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

    mApiClient = new GoogleApiClient.Builder(this)
            .addApi(Fitness.SENSORS_API)
            .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}
 
Example #21
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
private void registerFitnessDataListener(DataSource dataSource, DataType dataType) {

        SensorRequest request = new SensorRequest.Builder()
                .setDataSource( dataSource )
                .setDataType( dataType )
                .setSamplingRate( 3, TimeUnit.SECONDS )
                .build();

        Fitness.SensorsApi.add(mApiClient, request, this)
                .setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        if (status.isSuccess()) {
                            Log.e("GoogleFit", "SensorApi successfully added");
                        } else {
                            Log.e("GoogleFit", "adding status: " + status.getStatusMessage());
                        }
                    }
                });
    }
 
Example #22
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnected(Bundle bundle) {
    DataSourcesRequest dataSourceRequest = new DataSourcesRequest.Builder()
            .setDataTypes( DataType.TYPE_STEP_COUNT_CUMULATIVE )
            .setDataSourceTypes( DataSource.TYPE_RAW )
            .build();

    ResultCallback<DataSourcesResult> dataSourcesResultCallback = new ResultCallback<DataSourcesResult>() {
        @Override
        public void onResult(DataSourcesResult dataSourcesResult) {
            for( DataSource dataSource : dataSourcesResult.getDataSources() ) {
                if( DataType.TYPE_STEP_COUNT_CUMULATIVE.equals( dataSource.getDataType() ) ) {
                    registerFitnessDataListener(dataSource, DataType.TYPE_STEP_COUNT_CUMULATIVE);
                }
            }
        }
    };

    Fitness.SensorsApi.findDataSources(mApiClient, dataSourceRequest)
            .setResultCallback(dataSourcesResultCallback);
}
 
Example #23
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
@OnClick(R.id.btn_stop_session)
public void stopSession() {

    PendingResult<SessionStopResult> pendingResult =
            Fitness.SessionsApi.stopSession(mGoogleApiClient, mSession.getIdentifier());

    pendingResult.setResultCallback(new ResultCallback<SessionStopResult>() {
        @Override
        public void onResult(SessionStopResult sessionStopResult) {
            if( sessionStopResult.getStatus().isSuccess() ) {
                Log.i("Tuts+", "Successfully stopped session");
                if( sessionStopResult.getSessions() != null && !sessionStopResult.getSessions().isEmpty() ) {
                    Log.i("Tuts+", "Session name: " + sessionStopResult.getSessions().get(0).getName());
                    Log.i("Tuts+", "Session start: " + sessionStopResult.getSessions().get(0).getStartTime(TimeUnit.MILLISECONDS));
                    Log.i("Tuts+", "Session end: " + sessionStopResult.getSessions().get(0).getEndTime(TimeUnit.MILLISECONDS));
                }
            } else {
                Log.i("Tuts+", "Failed to stop session: " + sessionStopResult.getStatus().getStatusMessage());
            }
        }

    });
}
 
Example #24
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
@OnClick(R.id.btn_start_session)
public void startSession() {
    mSession = new Session.Builder()
            .setName(SESSION_NAME)
            .setIdentifier(getString(R.string.app_name) + " " + System.currentTimeMillis())
            .setDescription("Yoga Session Description")
            .setStartTime(Calendar.getInstance().getTimeInMillis(), TimeUnit.MILLISECONDS)
            .setActivity(FitnessActivities.YOGA)
            .build();

    PendingResult<Status> pendingResult =
            Fitness.SessionsApi.startSession(mGoogleApiClient, mSession);

    pendingResult.setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        Log.i("Tuts+", "Successfully started session");
                    } else {
                        Log.i("Tuts+", "Failed to start session: " + status.getStatusMessage());
                    }
                }
            }
    );
}
 
Example #25
Source File: DataManager.java    From GoogleFitExample with Apache License 2.0 5 votes vote down vote up
private void unsubscribeAll() {
    if (isConnected()) {
        Fitness.RecordingApi.listSubscriptions(mClient).setResultCallback(new ResultCallback<ListSubscriptionsResult>() {
            @Override
            public void onResult(ListSubscriptionsResult result) {
                for (Subscription sc : result.getSubscriptions()) {
                    DataType dt = sc.getDataType();
                    Log.i(TAG, "Unsubscribing: " + dt.getName());
                    Fitness.RecordingApi.unsubscribe(mClient, sc)
                            .setResultCallback(new ResultCallback<Status>() {
                                @Override
                                public void onResult(Status status) {
                                    if (status.isSuccess()) {
                                        Log.i(TAG, "Successfully unsubscribed for data type: step count delta");
                                    } else {
                                        // Subscription not removed
                                        Log.i(TAG, "Failed to unsubscribe for data type: step count delta");
                                    }
                                }
                            });
                }
            }
        });
    } else {
        Context context = getApplicationContext();
        if (context != null) {
            Toast.makeText(context, "Error: mClient not connected.", Toast.LENGTH_LONG).show();
        }
    }
}
 
Example #26
Source File: GoogleFit.java    From OpenFit with MIT License 5 votes vote down vote up
public void delData() {
    Calendar cal = Calendar.getInstance();
    Date now = new Date();
    cal.setTime(now);
    long endTime = cal.getTimeInMillis();
    cal.add(Calendar.WEEK_OF_YEAR, -4);
    long startTime = cal.getTimeInMillis();

    DataDeleteRequest delRequest = new DataDeleteRequest.Builder()
    .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
    .deleteAllData()
    .deleteAllSessions()
    .build();

    Fitness.HistoryApi.deleteData(mClient, delRequest)
    .setResultCallback(new ResultCallback<Status>() {
        @Override
        public void onResult(Status status) {
            if(status.isSuccess()) {
                Log.d(LOG_TAG, "Successfully deleted sessions");
            }
            else {
                Log.d(LOG_TAG, "Failed to delete sessions");
            }
        }
    });
}
 
Example #27
Source File: RecordingApi.java    From react-native-google-fit with MIT License 5 votes vote down vote up
public void subscribe(ReadableArray dataTypes) {
    ArrayList<String> dataTypesList = new ArrayList<String>();

    for (Object type : dataTypes.toArrayList()) {
        dataTypesList.add(type.toString());
    }


    for (String dataTypeName : dataTypesList) {
        DataType dataType = getDataType(dataTypeName);

        // Just skip unknown data types
        if (dataType == null) {
            continue;
        }

        final String eventName = getEventName(dataTypeName);

        Fitness.RecordingApi.subscribe(googleFitManager.getGoogleApiClient(), dataType)
                .setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(@NonNull Status status) {
                        WritableMap map = Arguments.createMap();

                        map.putString("type", eventName);

                        if (status.isSuccess()) {
                            map.putBoolean("recording", true);
                            Log.i(TAG, "RecordingAPI - Connected");
                            sendEvent(reactContext, eventName, map);
                        } else {
                            map.putBoolean("recording", false);
                            Log.i(TAG, "RecordingAPI - Error connecting");
                            sendEvent(reactContext, eventName, map);
                        }
                    }
                });
    }
}
 
Example #28
Source File: DataManager.java    From GoogleFitExample with Apache License 2.0 5 votes vote down vote up
private void listSubscriptions() {
    Fitness.RecordingApi.listSubscriptions(mClient).setResultCallback(new ResultCallback<ListSubscriptionsResult>() {
        @Override
        public void onResult(ListSubscriptionsResult result) {
            for (Subscription sc : result.getSubscriptions()) {
                DataType dt = sc.getDataType();
                Log.i(TAG, "found subscription for data type: " + dt.getName());
            }
        }
    });
}
 
Example #29
Source File: UserFragment.java    From android-kubernetes-blockchain with Apache License 2.0 5 votes vote down vote up
@Override
public void onPause() {
    super.onPause();

    // remove callbacks from refreshing
    handler.removeCallbacks(refreshRunnable);

    // set refreshing back to false if it was refreshing
    if (swipeRefreshLayout.isRefreshing()) {
        swipeRefreshLayout.setRefreshing(false);
    }

    // unregister the listener
    if (!GoogleSignIn.hasPermissions(GoogleSignIn.getLastSignedInAccount((AppCompatActivity) getActivity()))) {
        Log.d(TAG, "Not signed in...");
    } else {
        Fitness.getSensorsClient((AppCompatActivity) getActivity(), GoogleSignIn.getLastSignedInAccount((AppCompatActivity) getActivity()))
                .remove(stepListener)
                .addOnCompleteListener(
                        new OnCompleteListener<Boolean>() {
                            @Override
                            public void onComplete(@NonNull Task<Boolean> task) {
                                if (task.isSuccessful() && task.getResult()) {
                                    Log.d(TAG, "Step Listener for steps was removed.");
                                } else {
                                    Log.e(TAG, "Step Listener for steps was not removed.", task.getException());
                                }
                            }
                        }
                );
    }
}
 
Example #30
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initViews();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Fitness.HISTORY_API)
            .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
            .addConnectionCallbacks(this)
            .enableAutoManage(this, 0, this)
            .build();
}