簡體   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