23

i want to implement push notification in my application.i want to know,how we get the device token for push notification in android after enabling the google cloud messaging API.How can we get a device token for a particular device??

Tarique Shamsi
  • 331
  • 1
  • 2
  • 8

1 Answers1

24
try {
     InstanceID instanceID = InstanceID.getInstance(this);

     String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

            Log.i(TAG, "GCM Registration Token: " + token);

}catch (Exception e) {
            Log.d(TAG, "Failed to complete token refresh", e);
}
Nikunj
  • 3,937
  • 19
  • 33
  • 1
    in which part of project,we add these codes,and how we get the device token? – Tarique Shamsi Nov 06 '15 at 06:59
  • you can add above code in any Activity or Service. It's better to get token in Launcher Activity.And put your "SenderId" in R.string.gcm_defaultSenderId – Nikunj Nov 06 '15 at 07:16
  • 3
    but this code is working for registration token,actually i want the device token for particular android device.how can we get particular device token for android device – Tarique Shamsi Nov 06 '15 at 07:20
  • 1
    to integrate GCM in Android you only need "device token" which you get from above code and you have to send it to server. – Nikunj Nov 06 '15 at 11:29
  • InstanceID should be retrieved using `InstanceID.getInstance(context).getId();` – Louis Jan 24 '18 at 13:23