繁体   English   中英

在服务中获取每日步数数据(Google健身历史记录API)

[英]Get daily step data (google fit history api) in a service

我想实现一项服务,该服务每小时获取一次每日步长数据以执行此操作。

我使用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 Official App中显示的步数不匹配 您可以使用以下代码获取每天各种活动的步骤:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM