Androidプログラマへの道 〜 Moonlight 明日香 〜 - Google Play Servicesが有効か確認する
Google Play Servicesがインストールされているか, そして有効かを確認するためには, GooglePlayServicesUtilクラスを利用する.

Google Play Servicesの有効チェック

  • MainActivity.java
    • GooglePlayServicesUtil#isGooglePlayServicesAvailableメソッドで, Google Play Servicesが利用可能かチェックする.
    • エラーの場合, GooglePlayServicesUtil#isUserRecoverableErrorメソッドで, ユーザが対応可能なエラーかチェックする.
package com.moonlight_aska.android.googlemapv2;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {
  private GoogleMap mMap = null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Google Play Servicesを利用可能か
    int iRes = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (iRes == ConnectionResult.SUCCESS) {
      // 利用可能な場合
      mMap = ( (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map) ).getMap();
    }
    else if (GooglePlayServicesUtil.isUserRecoverableError(iRes)) {
      // ユーザが対応可能なエラー
      Dialog dialog = GooglePlayServicesUtil.getErrorDialog(iRes, this, 0);
      if (dialog != null) {
        GooglePlayServicesUtil.getErrorDialog(iRes, this, 1, new DialogInterface.OnCancelListener() {
          @Override
          public void onCancel(DialogInterface dialog) {
            // TODO Auto-generated method stub
            finish();
          }
        }).show();
      }
    }
    else {
      // ユーザでは対応不可
      Toast.makeText(this, "Google Play Services is not available.", Toast.LENGTH_LONG).show();
      finish();
    }
  }
}