2017-03-23 4 views
0

1時間に1回、毎日のステップデータを取得してそれを実行するサービスを実装したいと考えています。サービス内の毎日のステップデータ(Google適合履歴api)を取得する

MyGoogleApiClient_Singletonインスタンスを使用し、MainActivityを使用してクライアントにサービスを渡します。私は、助けのための感謝を継続する方法を知っているドント

マイ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)); 
} 

}

そして、私のサービス(それはdoesn't何かを)

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

} 

答えて

0

これらの関連するSOの投稿を参照してください:How to retrieve daily running and walking steps from Google Fit APIおよびStep count retrieved through Google Fit Api does not match Step count displayed in 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(); 

またフィットのAndroid APIとフィットREST APIを使用して、現在の日々のステップカウントデータを読み込む実証このdocumentationをチェックすることができます。

次の例に示すように、[HistoryApi.readDailyTotalhttps://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; 
    } 
} 
関連する問題