com.google.android.gms.iid.InstanceID Java Examples
The following examples show how to use
com.google.android.gms.iid.InstanceID.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IIDService.java From BackPackTrackII with GNU General Public License v3.0 | 6 votes |
public static void getToken(Context context, boolean refresh) { try { // Get token InstanceID instanceID = InstanceID.getInstance(context); String token = instanceID.getToken( context.getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); Log.i(TAG, "Token=" + token); // Store token SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putString(SettingsFragment.PREF_GCM_TOKEN, token).apply(); // Subscribe to topics GcmService.subscribeBroadcasts(context); GcmService.subscribeWeatherUpdates(context); } catch (IOException ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } }
Example #2
Source File: RegistrationIntentService.java From httpebble-android with MIT License | 6 votes |
@Override protected void onHandleIntent(Intent intent) { if (!TextUtils.isEmpty(Settings.getEmail(this)) && !TextUtils.isEmpty(Settings.getToken(this))) { try { JSONObject data = new JSONObject(); data.put("userId", Settings.getEmail(this)); data.put("userToken", Settings.getToken(this)); data.put("gcmId", InstanceID.getInstance(this).getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null)); data.put("purchased", Settings.hasPurchased(this) || BuildConfig.DEBUG); int code = HttpRequest.post("https://ofkorth.net/pebble/register") .send("data=" + data.toString()) .code(); if (code == 200) { Settings.setNeedToRegister(this, false); } else { Settings.setNeedToRegister(this, true); } } catch (IOException | JSONException e) { Settings.setNeedToRegister(this, true); } } }
Example #3
Source File: GCMProvider.java From OPFPush with Apache License 2.0 | 6 votes |
@Override @SuppressWarnings("PMD.PreserveStackTrace") public void run() { OPFLog.logMethod(); try { InstanceID.getInstance(getContext()).deleteToken(senderIDs, INSTANCE_ID_SCOPE); preferencesProvider.reset(); onUnregistrationSuccess(); } catch (IOException e) { OPFLog.i("Error while unregister GCM.", e); final String error = e.getMessage(); switch (error) { case GoogleCloudMessaging.ERROR_SERVICE_NOT_AVAILABLE: onServicesNotAvailable(); break; case GoogleCloudMessaging.ERROR_MAIN_THREAD: throw new WrongThreadException(false); default: onError(error); break; } } close(); }
Example #4
Source File: InstanceIdRpc.java From android_external_GmsLib with Apache License 2.0 | 6 votes |
private void sendRegisterMessage(Bundle data, KeyPair keyPair, String requestId) throws IOException { long elapsedRealtime = SystemClock.elapsedRealtime(); if (nextAttempt != 0 && elapsedRealtime <= nextAttempt) { Log.w(TAG, "Had to wait for " + interval + ", that's still " + (nextAttempt - elapsedRealtime)); throw new IOException(ERROR_BACKOFF); } initialize(); if (iidPackageName == null) { throw new IOException(ERROR_MISSING_INSTANCEID_SERVICE); } Intent intent = new Intent(ACTION_C2DM_REGISTER); intent.setPackage(iidPackageName); data.putString(EXTRA_GMS_VERSION, Integer.toString(getGmsVersionCode(context))); data.putString(EXTRA_OS_VERSION, Integer.toString(Build.VERSION.SDK_INT)); data.putString(EXTRA_APP_VERSION_CODE, Integer.toString(getSelfVersionCode(context))); data.putString(EXTRA_APP_VERSION_NAME, getSelfVersionName(context)); data.putString(EXTRA_CLIENT_VERSION, "iid-" + MAX_REFERENCE_VERSION); data.putString(EXTRA_APP_ID, InstanceID.sha1KeyPair(keyPair)); String pub = base64encode(keyPair.getPublic().getEncoded()); data.putString(EXTRA_PUBLIC_KEY, pub); data.putString(EXTRA_SIGNATURE, sign(keyPair, context.getPackageName(), pub)); intent.putExtras(data); intent.putExtra(EXTRA_APP, getSelfAuthToken()); sendRequest(intent, requestId); }
Example #5
Source File: RegistrationIntentService.java From ti.goosh with MIT License | 6 votes |
@Override protected void onHandleIntent(Intent intent) { TiGooshModule module = TiGooshModule.getModule(); if (module == null) { Log.e(LCAT, "Intent handled but no TiGoosh instance module found"); return; } try { String senderId = module.getSenderId(); String token = InstanceID.getInstance(this).getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); Log.i(LCAT, "Sender ID: " + senderId); Log.i(LCAT, "Device Token: " + token); module.sendSuccess(token); } catch (Exception ex) { Log.e(LCAT, "Failed to get GCM Registration Token:" + ex.getMessage()); module.sendError(ex); } }
Example #6
Source File: TiGooshModule.java From ti.goosh with MIT License | 6 votes |
@Kroll.method public void unregisterForPushNotifications() { final String senderId = getSenderId(); final Context context = TiApplication.getInstance().getApplicationContext(); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { InstanceID.getInstance(context).deleteToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE); Log.d(LCAT, "delete instanceid succeeded"); } catch (final IOException e) { Log.e(LCAT, "remove token failed - error: " + e.getMessage()); } return null; } }.execute(); }
Example #7
Source File: RegistrationIntentService.java From mattermost-android-classic with Apache License 2.0 | 6 votes |
@Override protected void onHandleIntent(Intent intent) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); try { synchronized (TAG) { InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(getString(R.string.gcm_sender_id), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); Log.d(TAG, "GCM registration token: " + token); sharedPreferences.edit().putString("device_id", token).apply(); } } catch (IOException e) { Log.d(TAG, "Failed to complete token refresh", e); } Intent registrationComplete = new Intent(RegistrationConstants.REGISTRATION_COMPLETE); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); }
Example #8
Source File: InstanceIDWithSubtype.java From 365browser with Apache License 2.0 | 5 votes |
@Override public void deleteInstanceID() throws IOException { // Synchronize on the base class, to match getInstance. synchronized (InstanceID.class) { sSubtypeInstances.remove(mSubtype); super.deleteInstanceID(); } }
Example #9
Source File: TokenRetriever.java From ello-android with MIT License | 5 votes |
public String getToken() { try { InstanceID instanceID = InstanceID.getInstance(context); String token = instanceID.getToken(context.getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); Log.d(TAG, "GCM Registration Token: " + token); return token; } catch (Exception e) { Log.d(TAG, "Failed to complete token refresh", e); return null; } }
Example #10
Source File: RegistrationIntentService.java From newsApp with Apache License 2.0 | 5 votes |
@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] InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); // [END get_token] Log.i(TAG, "GCM Registration Token: " + token); // 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(com.ghn.android.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(com.ghn.android.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); }
Example #11
Source File: GCMProvider.java From OPFPush with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("PMD.PreserveStackTrace") public void run() { OPFLog.logMethod(senderIDs); try { final String registrationId = InstanceID.getInstance(getContext()).getToken(senderIDs, INSTANCE_ID_SCOPE); if (TextUtils.isEmpty(registrationId)) { OPFLog.w("Registration id is empty"); onAuthError(); } else { OPFLog.d("Registration id isn't empty"); onRegistrationSuccess(registrationId); } } catch (IOException e) { OPFLog.i("Error while register GCM.", e); final String error = e.getMessage(); switch (error) { case GoogleCloudMessaging.ERROR_SERVICE_NOT_AVAILABLE: onServicesNotAvailable(); break; case GoogleCloudMessaging.ERROR_MAIN_THREAD: throw new WrongThreadException(false); default: onError(error); break; } } }
Example #12
Source File: GoogleCloudMessaging.java From android_external_GmsLib with Apache License 2.0 | 5 votes |
private String getFrom(String to) { int i = to.indexOf('@'); if (i > 0) { to = to.substring(0, i); } return InstanceID.getInstance(context).getStore().get("", to, INSTANCE_ID_SCOPE); }
Example #13
Source File: CloudMessagingRpc.java From android_external_GmsLib with Apache License 2.0 | 5 votes |
public String handleRegisterMessageResult(Intent resultIntent) throws IOException { if (resultIntent == null) throw new IOException(InstanceID.ERROR_SERVICE_NOT_AVAILABLE); String result = resultIntent.getStringExtra(EXTRA_REGISTRATION_ID); if (result == null) result = resultIntent.getStringExtra(EXTRA_UNREGISTERED); if (result != null) return result; result = resultIntent.getStringExtra(EXTRA_ERROR); throw new IOException(result != null ? result : InstanceID.ERROR_SERVICE_NOT_AVAILABLE); }
Example #14
Source File: GCMPushPlugin.java From GCMPushPlugin with MIT License | 5 votes |
private void unregisterGCM() { InstanceID instanceID = InstanceID.getInstance(cordova.getActivity()); try { instanceID.deleteInstanceID(); callback.success("Successfully unregistered from GCM"); } catch (IOException e) { e.printStackTrace(); callback.error("Unable to unregister from GCM: " + e.getLocalizedMessage()); } }
Example #15
Source File: GPPRegistrationIntentService.java From GCMPushPlugin with MIT License | 5 votes |
@Override protected void onHandleIntent(Intent intent) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); try { // In the (unlikely) event that multiple refresh operations occur simultaneously, // ensure that they are processed sequentially. synchronized (TAG) { // [START register_for_gcm] // Initially this call goes out to the network to retrieve the token, subsequent calls // are local. // [START get_token] final String projectId = intent.getExtras().getString(GCMPushPlugin.SENDER_ID_KEY); InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(projectId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); // [END get_token] // Log.i(TAG, "GCM Registration Token: " + 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(GCMPushPlugin.SENT_TOKEN_KEY, true).apply(); sharedPreferences.edit().putString(GCMPushPlugin.GCM_TOKEN_KEY, token).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(GCMPushPlugin.SENT_TOKEN_KEY, false).apply(); } // Notify UI that registration has completed, so the progress indicator can be hidden. Intent registrationComplete = new Intent(GCMPushPlugin.REG_COMPLETE_BROADCAST_KEY); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); }
Example #16
Source File: IDRegisterService.java From easygoogle with Apache License 2.0 | 5 votes |
@Override protected void onHandleIntent(Intent intent) { String senderId = intent.getStringExtra(MessagingFragment.SENDER_ID_ARG); String gcmPermissionName = intent.getStringExtra(MessagingFragment.GCM_PERMISSION_ARG); try { // Initially this call goes out to the network to retrieve the token, subsequent calls // are local. InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); Log.i(TAG, "GCM Registration Token: " + token); // Find any services that could handle this List<ComponentName> services = GCMUtils.findServices(this, gcmPermissionName); // Notify the services of a new token for (ComponentName cn : services) { Log.d(TAG, "Launching service: " + cn); Intent newTokenIntent = new Intent(); newTokenIntent.setComponent(cn); newTokenIntent.setAction(getString(R.string.action_new_token)); newTokenIntent.putExtra(EasyMessageService.EXTRA_TOKEN, token); startService(newTokenIntent); } } catch (Exception 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. Log.e(TAG, "Failed to complete token refresh", e); } }
Example #17
Source File: GCMRegistration.java From redalert-android with Apache License 2.0 | 5 votes |
public static void registerForPushNotifications(Context context) throws Exception { // Make sure we have Google Play Services if (!GooglePlayServices.isAvailable(context)) { // Throw exception throw new Exception(context.getString(R.string.noGooglePlayServices)); } // Get instance ID API InstanceID instanceID = InstanceID.getInstance(context); // Get a GCM registration token String token = instanceID.getToken(GCMGateway.SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); // Log to logcat Log.d(Logging.TAG, "GCM registration success: " + token); // Get GCM PubSub handler GcmPubSub pubSub = GcmPubSub.getInstance(context); // Subscribe to alerts topic // (limited to 1M subscriptions app-wide - think about how to scale this when the time comes) pubSub.subscribe(token, GCMGateway.ALERTS_TOPIC, null); // Log it Log.d(Logging.TAG, "GCM subscription success: " + GCMGateway.ALERTS_TOPIC); // Prepare an object to store and send the registration token to our API RegistrationRequest register = new RegistrationRequest(token, API.PLATFORM_IDENTIFIER); // Send the request to our API HTTP.post(API.API_ENDPOINT + "/register", Singleton.getJackson().writeValueAsString(register)); // Persist it locally saveRegistrationToken(context, token); }
Example #18
Source File: GCMModule.java From gcmpush with Apache License 2.0 | 5 votes |
public String getToken(String senderId){ // get token and return it try { InstanceID instanceID = InstanceID.getInstance(TiApplication.getInstance()); return instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); } catch (Exception ex) { return null; } }
Example #19
Source File: GCMRegistrationIntentService.java From pusher-websocket-android with MIT License | 5 votes |
@Override protected void onHandleIntent(Intent intent) { final InstanceID instanceID = InstanceID.getInstance(this); final String defaultSenderId = intent.getStringExtra("gcm_defaultSenderId"); Intent gcmCalled = new Intent(PushNotificationRegistration.GCM_CALLED_INTENT_FILTER); int retryAttempts = 0; String token = null; while (token == null && retryAttempts < INSTANCE_ID_RETRY_ATTEMPTS){ try { token = instanceID.getToken(defaultSenderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); } catch (IOException e) { Log.d(TAG, "Failed to get token from InstanceID", e); } finally { retryAttempts++; } } if(token == null){ Log.e(TAG, "Failed to get token after " + INSTANCE_ID_RETRY_ATTEMPTS + " attempts."); } gcmCalled.putExtra(PushNotificationRegistration.TOKEN_EXTRA_KEY, token); LocalBroadcastManager.getInstance(this).sendBroadcast(gcmCalled); }
Example #20
Source File: InstanceIDWithSubtype.java From 365browser with Apache License 2.0 | 5 votes |
/** * Returns an instance of this class. Unlike {@link InstanceID#getInstance(Context)}, it is not * a singleton, but instead a different instance will be returned for each {@code subtype}. */ public static InstanceIDWithSubtype getInstance(Context context, String subtype) { if (TextUtils.isEmpty(subtype)) { throw new IllegalArgumentException("subtype must not be empty"); } context = context.getApplicationContext(); // Synchronize on the base class, to match the synchronized statements in // InstanceID.getInstance. synchronized (InstanceID.class) { if (sSubtypeInstances.isEmpty() && sFakeFactoryForTesting == null) { // The static InstanceID.getInstance method performs some one-time initialization // logic that is also necessary for users of this sub-class. To work around this, // first get (but don't use) the default InstanceID. InstanceID.getInstance(context); } InstanceIDWithSubtype existing = sSubtypeInstances.get(subtype); if (existing == null) { if (sFakeFactoryForTesting != null) { existing = sFakeFactoryForTesting.create(context, subtype); } else { existing = new InstanceIDWithSubtype(context, subtype); } sSubtypeInstances.put(subtype, existing); } return existing; } }
Example #21
Source File: RNPushNotificationRegistrationService.java From react-native-push-notification-CE with MIT License | 5 votes |
@Override protected void onHandleIntent(Intent intent) { try { String SenderID = intent.getStringExtra("senderID"); InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(SenderID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); sendRegistrationToken(token); } catch (Exception e) { Log.e(LOG_TAG, TAG + " failed to process intent " + intent, e); } }
Example #22
Source File: GetGcmServerToken.java From RxGcm with Apache License 2.0 | 5 votes |
String retrieve(Context context) throws Exception { int status = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context); if(status != ConnectionResult.SUCCESS) throw new RuntimeException(Constants.GOOGLE_PLAY_SERVICES_ERROR); InstanceID instanceID = InstanceID.getInstance(context); return instanceID.getToken(context.getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); }
Example #23
Source File: MyRegistrationIntentService.java From openshop.io-android with MIT License | 5 votes |
@Override protected void onHandleIntent(Intent intent) { 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] InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); // [END get_token] Timber.d("GCM token obtained: %s", token); // Send token to third party only if not already registered. if (!SettingsMy.getTokenSentToServer()) { boolean success = sendRegistrationToServer(token); // Subscribe to topic channels. Not implemented now. 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. SettingsMy.setTokenSentToServer(success); } // [END register_for_gcm] } catch (Exception e) { Timber.e(e, "Failed to complete token refresh"); // 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. SettingsMy.setTokenSentToServer(false); } // Notify UI that registration has completed, so the progress indicator can be hidden. Intent registrationComplete = new Intent(SettingsMy.REGISTRATION_COMPLETE); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); }
Example #24
Source File: RegistrationIntentService.java From gcm-android-client with Apache License 2.0 | 5 votes |
/** * Register for token for the specified sender Id * * @param instanceID instance of {@link InstanceID} associated with the sender Id * @param senderId Sender ID for which the token has to be deleted */ private String registerForToken(InstanceID instanceID, String senderId) throws IOException { String token = instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); if(GcmHelper.DEBUG_ENABLED)Log.i(GcmHelper.TAG, "PushRegistrationService: GCM Registration Token: " + token); //Notify the helper that the push token has been updated GcmHelper.getInstance().tokenUpdated(getApplicationContext(), token); return token; }
Example #25
Source File: InstanceIdHelper.java From gcm with Apache License 2.0 | 5 votes |
public void deleteInstanceIdInBackground() { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { InstanceID.getInstance(mContext).deleteInstanceID(); mLogger.log(Log.INFO, "delete instanceId succeeded."); MainActivity.showToast(mContext, R.string.iid_delete_token_toast_success); // Remove all appTokens and topics subscriptions tied to any Sender. for (int i = 0; i < mSenders.getSenders().size(); i++) { Sender sender = mSenders.getSenders().valueAt(i); boolean senderIsDirty = false; if (sender.appTokens.size() > 0) { sender.appTokens.clear(); senderIsDirty = true; } for (String topic : sender.topics.keySet()) { if (sender.topics.get(topic)) { sender.topics.put(topic, false); senderIsDirty = true; } } if (senderIsDirty) { mSenders.updateSender(sender); } } } catch (final IOException e) { mLogger.log(Log.INFO, "delete instanceId failed.\nerror: " + e.getMessage()); MainActivity.showToast(mContext, R.string.iid_toast_error, e.getMessage()); } return null; } }.execute(); }
Example #26
Source File: RegistrationIntentService.java From Advanced_Android_Development with Apache License 2.0 | 5 votes |
@Override protected void onHandleIntent(Intent intent) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); try { // In the (unlikely) event that multiple refresh operations occur simultaneously, // ensure that they are processed sequentially. synchronized (TAG) { // Initially this call goes out to the network to retrieve the token, subsequent calls // are local. InstanceID instanceID = InstanceID.getInstance(this); // TODO: gcm_default sender ID comes from the API console String senderId = getString(R.string.gcm_defaultSenderId); if ( senderId.length() != 0 ) { String token = instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); sendRegistrationToServer(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(MainActivity.SENT_TOKEN_TO_SERVER, true).apply(); } } 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(MainActivity.SENT_TOKEN_TO_SERVER, false).apply(); } }
Example #27
Source File: RegistrationIntentService.java From friendlyping with Apache License 2.0 | 5 votes |
@Override protected void onHandleIntent(Intent intent) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); try { // Just in case that onHandleIntent has been triggered several times in short // succession. synchronized (TAG) { InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); Log.d(TAG, "GCM registration token: " + token); // Register to the server and subscribe to the topic of interest. sendRegistrationToServer(token); // The list of topics we can subscribe to is being implemented within the server. GcmPubSub.getInstance(this).subscribe(token, "/topics/newclient", null); final SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(RegistrationConstants.SENT_TOKEN_TO_SERVER, true); editor.putString(RegistrationConstants.TOKEN, token); editor.apply(); } } catch (IOException e) { Log.d(TAG, "Failed to complete token refresh", e); sharedPreferences.edit().putBoolean(RegistrationConstants. SENT_TOKEN_TO_SERVER, false).apply(); } Intent registrationComplete = new Intent(RegistrationConstants.REGISTRATION_COMPLETE); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); }
Example #28
Source File: RegistrationIntentService.java From google-services with Apache License 2.0 | 5 votes |
@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] InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); // [END get_token] Log.i(TAG, "GCM Registration Token: " + token); // 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); }
Example #29
Source File: InstanceIdHelper.java From gcm with Apache License 2.0 | 4 votes |
public long getCreationTime() { return InstanceID.getInstance(mContext).getCreationTime(); }
Example #30
Source File: PubSubService.java From easygoogle with Apache License 2.0 | 4 votes |
private String getToken(String senderId) throws IOException { InstanceID instanceID = InstanceID.getInstance(this); return instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); }