ラベル GCM の投稿を表示しています。 すべての投稿を表示
ラベル GCM の投稿を表示しています。 すべての投稿を表示

2014年1月21日火曜日

Google Play ServicesでGCMを使ってみる(Google Play Services APKの存在チェック編)

詰まったところをピンポイントで覚え書き。
GCMを使おうとSDK Managerで「Google Cloud Messaging for Android Library」をインストール。。。
Derecatedになってるぞ!
GCMのオフィシャルサイトで確認してみると、「Google Play Services」を使いなさいとのこと。
いつの間に変わったのよ!?って、Google I/O 2013の時ですよね。そいえば中継見てましたよ。時間的にめっちゃ眠かった(笑)
そんなこんなでオフィシャルサイトの「Implementing GCM Client」ページを見ながら環境作りました。書いてあるまんま! とりあえずPlay ServicesのAPKがあるかどうかをチェックする必要があるらしいので、そこだけ書いて動かしてみよう。
ManifestにパーミッションとReceiverを追加しておけばよし。ここはGoogle Play Servicesに変わる前と一緒みたい。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.helloworld.app" >
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="com.helloworld.app.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.helloworld.app.permission.C2D_MESSAGE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:theme="@style/Theme.AppCompat"
            android:name="com.helloworld.app.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.helloworld.app" />
            </intent-filter>
        </receiver>
        <service android:name=".GcmIntentService" />
    </application>
</manifest>
で、チェック用のメソッドがこれ。
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Log.i(TAG, "This device is not supported.");
            finish();
        }
        return false;
    }
    return true;
}