我想实现一个服务,每小时一次获取每日步数数据以使用它做事。
我使用 MyGoogleApiClient_Singleton
实例和 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));
}
}
和我的服务(它不做任何事情(
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);
}
}
我不知道如何继续,感谢您的帮助
您可以参考以下相关的SO帖子:如何从Google Fit API检索每日跑步和步行步数,以及通过Google Fit Api检索的步数与Google Fit官方应用程序中显示的步数不匹配。可以使用以下代码获取每天各种活动的步骤:
DataReadRequest readRequest = new DataReadRequest.Builder()
.aggregate(ESTIMATED_STEP_DELTAS, DataType.AGGREGATE_STEP_COUNT_DELTA)
.bucketByActivityType(1, TimeUnit.SECONDS)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build();
您还可以查看此文档,其中演示了如何使用 Fit Android API 和 Fit REST API 读取当前的每日步数数据。
您的应用可以通过调用 [ 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((来读取当前的每日总步数,如以下示例所示:
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;
}
}