GoogleAPIClientの作成と接続

ツイート このエントリーをはてなブックマークに追加
1つ上へ / ブログトップへ

Google Fit APIはGoogle Play Serviceで提供されています。本記事では、下準備としてGoogleAPIClientの作成と接続までを紹介します。

Google Play Serviceの追加

build.gradleに次のエントリーをdependenciesに追加します。

dependencies {
    compile 'com.google.android.gms:play-services:5.2.08'
}

interfaceを実装する

FragmentかActivityに次のinterfaceを実装します。覚えるのは正直面倒なのでIDEに頼ったほうがよいでしょう。

  • GoogleApiClient.ConnectionCallbacks
  • GoogleApiClient.OnConnectionFailedListener

onCreate()でGoogleAPIClientのインスタンスを作成する

今回はGoogle Fit APIを使用するので、addApi()でFitness.APIを指定します。

void createAPIClient() {
  // Create the Google API Client
  mApiClient = new GoogleApiClient.Builder(activity)
    // select the Fitness API
    .addApi(Fitness.API)
    // specify the scopes of access
    .addScope(FitnessScopes.SCOPE_ACTIVITY_READ)
    .addScope(FitnessScopes.SCOPE_BODY_READ_WRITE)
    // provide callbacks
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .build();
}

addConnectionCallbacks()とaddOnConnectionFailedListener()にthisを指定し、IDEの機能でimplementsを追加するのが手っ取り早いですね。

onStart()で接続する

まだ接続されていなければここでconnect()を呼んで接続します。

@Override
public void onStart() {
  super.onStart();
  if (!mApiClient.isConnected()) {
    // Connect the Google API client
    mApiClient.connect();
  }
}

Callbackの処理を実装する

接続成功 / 失敗時の処理を実装します。Googleのサンプルそのまんまですが。。。

// 接続成功時に呼ばれる
@Override
public void onConnected(Bundle bundle) {
  Log.v(TAG, "Connected");
  setButtonEnable(true);
}

// 接続が中断された時に呼ばれる。原因は引数で渡される
@Override
public void onConnectionSuspended(int i) {
  if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
    Log.v(TAG, "Connection lost.  Cause: Network Lost.");
  } else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
    Log.v(TAG, "Connection lost.  Reason: Service Disconnected");
  }
}

// 接続失敗時に呼ばれる。認証が必要な場合もこちら
@Override
public void onConnectionFailed(ConnectionResult result) {
  Activity activity = getActivity();
  if (activity == null) { return; }

  // Error while connecting. Try to resolve using the pending intent returned.
  if (result.getErrorCode() == ConnectionResult.SIGN_IN_REQUIRED ||
      result.getErrorCode() == FitnessStatusCodes.NEEDS_OAUTH_PERMISSIONS) {
    try {
      // Request authentication
      result.startResolutionForResult(activity, REQUEST_OAUTH);
    } catch (IntentSender.SendIntentException e) {
      Log.v(TAG, "Exception connecting to the fitness service : " + e.getMessage());
    }
  } else {
    Log.v(TAG, "Unknown connection issue. Code = " + result.getErrorCode());
  }
}

// 認証が終わった時の処理をここに記述しておくn
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  switch (requestCode) {
    case REQUEST_OAUTH:
      if (resultCode != Activity.RESULT_OK) { return; }

      mApiClient.connect();
      return;
  }
}
1つ上へ / ブログトップへ