I'm trying to implement the GCM service in my application, but I'm having trouble sending the TOKEN to my server. Please help me with this problem. Even in my class does not print logs in my logcat. However, when I run the app it generates the following:
02-26 11:32:29.684 11399-11537/mycompany I/b: Sending API token request. 02-26 11:32:30.025 11399-11537/mycompany I/b: Received API Token: AH0uPGGC ... zZfMp / Expires in: 432000000ms 02-26 11:32:30.034 11399-11537/mycompany I/g: Saved auth token I want to take this token and send it to my server. Thank you! See my code below: *AndroidManifest.xml* ... <!-- [START gcm_permission] --> <uses-permission android:name= "com.google.android.c2dm.permission.RECEIVE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <!-- [END gcm_permission] --> <permission android:name="mycompany.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="mycompany.permission.C2D_MESSAGE" /> ... <!-- [START gcm_listener] --> <service android:name="mycompany.GCM.MyGcmListenerService" android:exported="false" > <intent-filter> <action android:name= "com.google.android.c2dm.intent.RECEIVE" /> </intent-filter> </service> <!-- [END gcm_listener] --> <!-- [START instanceId_listener] --> <service android:name="mycompany.GCM.MyInstanceIDListenerService" android:exported="false"> <intent-filter> <action android:name= "com.google.android.gms.iid.InstanceID"/> </intent-filter> </service> <!-- [END instanceId_listener] --> <service android:name="mycompany.GCM.RegistrationIntentService" android:exported="false"> </service> ... *MyGcmListenerService.java* ... public class MyGcmListenerService extends GcmListenerService { private static final String TAG = "MyGcmListenerService"; /** * Called when message is received. * * * @param from SenderID of the sender. * @param data Data bundle containing message data as key/value pairs. * For Set of keys use data.keySet(). */ // [START receive_message] @Override public void onMessageReceived(String from, Bundle data) { String message = data.getString("message"); Log.d(TAG, "From: " + from); Log.d(TAG, "Message: " + message); if (from.startsWith("/topics/")) { // message received from some topic. } else { // normal downstream message. } // [START_EXCLUDE] /** * Production applications would usually process the message here. * Eg: - Syncing with server. * - Store message in local database. * - Update UI. */ /** * In some cases it may be useful to show a notification indicating to the user * that a message was received. */ sendNotification(message); // [END_EXCLUDE] } // [END receive_message] /** * Create and show a simple notification containing the received GCM message. * * @param message GCM message received. */ private void sendNotification(String message) { Intent intent = new Intent(this, MapActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); Bitmap bm = BitmapFactory.decodeResource(getResources(), R. drawable.icone); Uri defaultSoundUri = RingtoneManager.getDefaultUri( RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.icone2) .setLargeIcon(bm) .setContentTitle("Title") .setContentText(message) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE); notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); } } *MyInstanceIDListenerService.java* public class MyInstanceIDListenerService extends InstanceIDListenerService { private static final String TAG = "MyInstanceIDLS"; /** * Called if InstanceID token is updated. This may occur if the security of * the previous token had been compromised. This call is initiated by the * InstanceID provider. */ // [START refresh_token] @Override public void onTokenRefresh() { // Fetch updated Instance ID token and notify our app's server of any changes (if applicable). Intent intent = new Intent(this, RegistrationIntentService.class ); startService(intent); } // [END refresh_token] } *QuickstartPreferences.java* public class QuickstartPreferences { public static final String SENT_TOKEN_TO_SERVER = "sentTokenToServer"; public static final String REGISTRATION_COMPLETE = "registrationComplete"; } *RegistrationIntentService.java* public class RegistrationIntentService extends IntentService { private static final String TAG = "RegIntentService"; private static final String[] TOPICS = {"global"}; public RegistrationIntentService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { SharedPreferences sharedPreferences = PreferenceManager. getDefaultSharedPreferences(this); try { // [START register_for_gcm] // Initially this call goes out to the network to retrieve the token, subsequent calls // are local. // R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json. // See https://developers.google.com/cloud-messaging/android/start for details on this file. // [START get_token] String authorizedEntity = "XXXXXXXX"; // Project id from Google Developers Console String scope = "GCM"; // e.g. communicating using GCM, but you can use any //InstanceID instanceID = InstanceID.getInstance(this); String token = InstanceID.getInstance(this).getToken( authorizedEntity,scope); // String token = instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); //send token to app server Log.d(TAG, "GCM Registration Token: " + token); //NOT PRINT // TODO: Implement this method to send any registration to your app's servers. sendRegistrationToServer(token); // Subscribe to topic channels subscribeTopics(token); // You should store a boolean that indicates whether the generated token has been // sent to your server. If the boolean is false, send the token to your server, // otherwise your server should have already received the token. sharedPreferences.edit().putBoolean(QuickstartPreferences. SENT_TOKEN_TO_SERVER, true).apply(); // [END register_for_gcm] } catch (Exception e) { Log.d(TAG, "Failed to complete token refresh", e); // If an exception happens while fetching the new token or updating our registration data // on a third-party server, this ensures that we'll attempt the update at a later time. sharedPreferences.edit().putBoolean(QuickstartPreferences. SENT_TOKEN_TO_SERVER, false).apply(); } // Notify UI that registration has completed, so the progress indicator can be hidden. Intent registrationComplete = new Intent(QuickstartPreferences. REGISTRATION_COMPLETE); LocalBroadcastManager.getInstance(this).sendBroadcast( registrationComplete); } /** * Persist registration to third-party servers. * * Modify this method to associate the user's GCM registration token with any server-side account * maintained by your application. * * @param token The new token. */ private void sendRegistrationToServer(String token) { // Add custom implementation, as needed. //Enviar para servidor Log.e("TOKEN:", token); //NOT PRINT HttpURLConnection connection; OutputStreamWriter request = null; URL url = null; String response = null; String param = "dtoken="+token+"&dtype=Android"; try { url = new URL("http://myurl.com/action.php"); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestMethod("POST"); request = new OutputStreamWriter(connection.getOutputStream ()); request.write(param); request.flush(); request.close(); String line = ""; InputStreamReader isr = new InputStreamReader(connection. getInputStream()); BufferedReader reader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } isr.close(); reader.close(); } catch (IOException e) { // Error } } /** * Subscribe to any GCM topics of interest, as defined by the TOPICS constant. * * @param token GCM token * @throws IOException if unable to reach the GCM PubSub service */ // [START subscribe_topics] private void subscribeTopics(String token) throws IOException { GcmPubSub pubSub = GcmPubSub.getInstance(this); for (String topic : TOPICS) { pubSub.subscribe(token, "/topics/" + topic, null); } } // [END subscribe_topics] } Thanks for helping me! -- You received this message because you are subscribed to the Google Groups "Android Developers" group. To unsubscribe from this group and stop receiving emails from it, send an email to android-developers+unsubscr...@googlegroups.com. To post to this group, send email to android-developers@googlegroups.com. Visit this group at https://groups.google.com/group/android-developers. To view this discussion on the web visit https://groups.google.com/d/msgid/android-developers/e5eb28bb-a8bf-492c-9166-4a8e837cdbb8%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.