Reputation: 11
I want to implement a service that once per hour get the daily step data to do things with it.
I pass the client to the service using a MyGoogleApiClient_Singleton
instance and in the MainActivity.
My MainActivity
public class MainActivity extends AppCompatActivity {
public static final String TAG = "StepCounter";
private GoogleApiClient mClient = null;
TextView tv;
long total;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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();
buildFitnessClient();
tv=(TextView)findViewById(R.id.title_text_view);
//inicializamos el servicio
startService(new Intent(this, DatabaseUpload.class));
}
/**
* Build a {@link GoogleApiClient} to authenticate the user and allow the application
* to connect to the Fitness APIs. The included scopes should match the scopes needed
* by your app (see the documentation for details).
* Use the {@link GoogleApiClient.OnConnectionFailedListener}
* to resolve authentication failures (for example, the user has not signed in
* before, or has multiple accounts and must specify which account to use).
*/
private void buildFitnessClient() {
// Create the Google API Client
mClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.RECORDING_API)
.addApi(Fitness.HISTORY_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.addConnectionCallbacks(
new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected!!!");
// Now you can make calls to the Fitness APIs. What to do?
// Subscribe to some data sources!
subscribe();
}
@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.w(TAG, "Connection lost. Cause: Network Lost.");
} else if (i == ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.w(TAG, "Connection lost. Reason: Service Disconnected");
}
}
}
)
.enableAutoManage(this, 0, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.w(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();
MyGoogleApiClient_Singleton.getInstance(mClient);
}
/**
* Record step data by requesting a subscription to background step data.
*/
public void subscribe() {
// To create a subscription, invoke the Recording API. As soon as the subscription is
// active, fitness data will start recording.
Fitness.RecordingApi.subscribe(mClient, DataType.TYPE_STEP_COUNT_CUMULATIVE)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
if (status.getStatusCode()
== FitnessStatusCodes.SUCCESS_ALREADY_SUBSCRIBED) {
Log.i(TAG, "Existing subscription for activity detected.");
new VerifyDataTask().execute();
} else {
Log.i(TAG, "Successfully subscribed!");
new VerifyDataTask().execute();
}
} else {
Log.w(TAG, "There was a problem subscribing.");
}
}
});
}
/**
* Read the current daily step total, computed from midnight of the current day
* on the device's current timezone.
*/
private class VerifyDataTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
Log.i(TAG, "step count");
total = 0;
PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(mClient, DataType.TYPE_STEP_COUNT_DELTA);
DailyTotalResult totalResult = result.await(30, TimeUnit.SECONDS);
if (totalResult.getStatus().isSuccess()) {
DataSet totalSet = totalResult.getTotal();
total = totalSet.isEmpty()
? 0
: totalSet.getDataPoints().get(0).getValue(Field.FIELD_STEPS).asInt();
} else {
Log.w(TAG, "There was a problem getting the step count.");
}
Log.i(TAG, "Total steps: " + total);
return null;
}
}
private void readData() {
new VerifyDataTask().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the main; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
long pasos;
int id = item.getItemId();
if (id == R.id.action_read_data) {
readData();
pasos = total;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor edit = sp.edit();
edit.putLong("pasos",pasos);
edit.commit();
topasos();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Initialize a custom log class that outputs both to in-app targets and logcat.
*/
private void initializeLogging() {
// Wraps Android's native log framework.
LogWrapper logWrapper = new LogWrapper();
// Using Log, front-end to the logging chain, emulates android.util.log method signatures.
Log.setLogNode(logWrapper);
// Filter strips out everything except the message text.
MessageOnlyLogFilter msgFilter = new MessageOnlyLogFilter();
logWrapper.setNext(msgFilter);
// On screen logging via a customized TextView.
Log.i(TAG, "Ready");
}
void topasos(){
startActivity(new Intent(getBaseContext(), Cuenta.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP));
}
}
And my service (it doesn´t do anything)
public class DatabaseUpload extends Service {
GoogleApiClient mClient;
String TAG ="DataUpdate";
@Override
public void onCreate() {
super.onCreate();
mClient=MyGoogleApiClient_Singleton.getInstance(null).get_GoogleApiClient();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
}
I don´t know how to continue, thanks for the help
Upvotes: 1
Views: 4612
Reputation: 13469
You may refer with these related SO posts: How to retrieve daily running and walking steps from Google Fit API and Step count retrieved through Google Fit Api does not match Step count displayed in Google Fit Official App. You can get steps for various activities for each day by using the following code:
DataReadRequest readRequest = new DataReadRequest.Builder()
.aggregate(ESTIMATED_STEP_DELTAS, DataType.AGGREGATE_STEP_COUNT_DELTA)
.bucketByActivityType(1, TimeUnit.SECONDS)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build();
You may also check this documentation which demonstrates reading current daily step count data using the Fit Android API and Fit REST API.
Your app can read the current daily step total by calling [HistoryApi.readDailyTotal
](https://developers.google.com/android/reference/com/google/android/gms/fitness/HistoryApi.html#readDailyTotal(com.google.android.gms.common.api.GoogleApiClient, com.google.android.gms.fitness.data.DataType)), as shown in the following example:
private class VerifyDataTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
long total = 0;
PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(mClient, DataType.TYPE_STEP_COUNT_DELTA);
DailyTotalResult totalResult = result.await(30, TimeUnit.SECONDS);
if (totalResult.getStatus().isSuccess()) {
DataSet totalSet = totalResult.getTotal();
total = totalSet.isEmpty()
? 0
: totalSet.getDataPoints().get(0).getValue(Field.FIELD_STEPS).asInt();
} else {
Log.w(TAG, "There was a problem getting the step count.");
}
Log.i(TAG, "Total steps: " + total);
return null;
}
}
Upvotes: 2