AndroidでDevice Tokenの取得

sample

https://developers.google.com/cloud-messaging/android/start

https://github.com/googlesamples/google-services.git

方法

app/build.gradleのdependenciesに追記

compile 'com.google.android.gms:play-services-gcm:8.4.0'

res/value/string.xmlにSenderIDを追加

SenderIDはCloud Messaging  |  Google Developersから取得

<string name="gcm_defaultSenderId">0000000000000000</string>

RegistrationIntentServiceクラスを作成

class RegistrationIntentService : IntentService("RegIntentService") {

    private val TAG = "RegIntentService"

    override fun onHandleIntent(intent: Intent) {

        try {
            val instanceID = InstanceID.getInstance(this)
            val token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null)

            // TODO: Implement this method to send any registration to your app's servers.
            sendRegistrationToServer(token)

            //SharedPreferencesにデバイストークンを保存する処理など

        } catch (e: Exception) {
            Log.d(TAG, "Failed to complete token refresh", e)
            //SharedPreferencesに保存されているデバイストークンを削除する処理など
        }
    }

    private fun sendRegistrationToServer(token: String) {
        //なんらかの処理
    }

}

デバイストークンを取得する側に追記

class HogeFragment: Fragment(){
    private val PLAY_SERVICES_RESOLUTION_REQUEST = 9000
    private val TAG = "HogeFragment"
    
    ~デバイストークンを取得したいところで~
        if (checkPlayServices()) {
            // Start IntentService to register this application with GCM.
            val intent = Intent(activity, RegistrationIntentService::class.java)
            activity.startService(intent)
        }
    ~~~~~~~~~~~~~~~~~~~
    
    private fun checkPlayServices(): Boolean {
        val apiAvailability = GoogleApiAvailability.getInstance()
        val resultCode = apiAvailability.isGooglePlayServicesAvailable(activity)
        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(activity, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show()
            } else {
                Log.i(TAG, "This device is not supported.")
            }
            return false
        }
        return true
    }
}

マニフェストファイルに追記

<service android:name=".utility.RegistrationIntentService"></service>

参考

http://techbooster.jpn.org/andriod/application/1570/