Java Code Examples for com.google.android.gms.gcm.GoogleCloudMessaging

The following are top voted examples for showing how to use com.google.android.gms.gcm.GoogleCloudMessaging. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: PeSanKita-android   File: GcmBroadcastReceiver.java   Source Code and License 7 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
  GoogleCloudMessaging gcm         = GoogleCloudMessaging.getInstance(context);
  String               messageType = gcm.getMessageType(intent);

  if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
    Log.w(TAG, "GCM message...");

    if (!TextSecurePreferences.isPushRegistered(context)) {
      Log.w(TAG, "Not push registered!");
      return;
    }

    String messageData = intent.getStringExtra("message");
    String receiptData = intent.getStringExtra("receipt");

    if      (!TextUtils.isEmpty(messageData)) handleReceivedMessage(context, messageData);
    else if (!TextUtils.isEmpty(receiptData)) handleReceivedMessage(context, receiptData);
    else if (intent.hasExtra("notification")) handleReceivedNotification(context);
  }
}
 
Example 2
Project: PeSanKita-android   File: AdvancedPreferenceFragment.java   Source Code and License 6 votes vote down vote up
@Override
protected Integer doInBackground(Void... params) {
  try {
    Context                     context        = getActivity();
    SignalServiceAccountManager accountManager = AccountManagerFactory.createManager(context);

    try {
      accountManager.setGcmId(Optional.<String>absent());
    } catch (AuthorizationFailedException e) {
      Log.w(TAG, e);
    }

    if (!TextSecurePreferences.isGcmDisabled(context)) {
      GoogleCloudMessaging.getInstance(context).unregister();
    }

    return SUCCESS;
  } catch (IOException ioe) {
    Log.w(TAG, ioe);
    return NETWORK_ERROR;
  }
}
 
Example 3
Project: PeSanKita-android   File: GcmRefreshJob.java   Source Code and License 6 votes vote down vote up
@Override
public void onRun() throws Exception {
  if (TextSecurePreferences.isGcmDisabled(context)) return;

  Log.w(TAG, "Reregistering GCM...");
  int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);

  if (result != ConnectionResult.SUCCESS) {
    notifyGcmFailure();
  } else {
    String gcmId = GoogleCloudMessaging.getInstance(context).register(REGISTRATION_ID);
    textSecureAccountManager.setGcmId(Optional.of(gcmId));

    TextSecurePreferences.setGcmRegistrationId(context, gcmId);
    TextSecurePreferences.setWebsocketRegistered(context, true);
  }
}
 
Example 4
Project: twilio-voice-phonegap-plugin   File: GCMRegistrationService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    Log.d(TAG,"GCMRegistrationService: onHandleIntent()");
    try {
        InstanceID instanceID = InstanceID.getInstance(this);
        int gcmSenderIDIdentifier = getResources().getIdentifier("gcm_sender_id", "string", getPackageName());
        String gcmSenderId = getString(gcmSenderIDIdentifier);
        Log.d(TAG, "GCM Sender ID: " + gcmSenderId);
        String token = instanceID.getToken(gcmSenderId,
                GoogleCloudMessaging.INSTANCE_ID_SCOPE,
                null);
        Log.d(TAG, "Retrieved GCM Token: " + token);
        sendGCMTokenToActivity(token);
    } catch (Exception e) {
        /*
         * If we are unable to retrieve the GCM token we notify the Plugin
         * letting the user know this step failed.
         */
        Log.e(TAG, "Failed to retrieve GCM token", e);
        sendGCMTokenToActivity(null);
    }
}
 
Example 5
Project: CryptoVoice   File: GcmIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty() && GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
        Log.w("GCM", extras.toString());
        Intent i = new Intent(this, Main.class);// change the context and activity name.
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED +
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD +
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON +
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        this.startActivity(i);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Intent incoming = new Intent("INCOMING");
        incoming.putExtra("number", extras.getString("message"));
        sendBroadcast(incoming);
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}
 
Example 6
Project: GarageDoor   File: GarageDoorIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Play a click sound and vibrate quickly
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    AudioManager audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
    audioManager.playSoundEffect(SoundEffectConstants.CLICK, 1.0f);
    Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
    vibrator.vibrate(VIBRATOR_PULSE);

    try {
        Bundle data = new Bundle();
        data.putString("user",
                sharedPreferences.getString(GarageDoorWidgetProvider.PREF_USERNAME, ""));
        data.putString("password",
                sharedPreferences.getString(GarageDoorWidgetProvider.PREF_PASSWORD, ""));
        data.putString("timestamp", String.valueOf(System.currentTimeMillis() / 1000));

        String id = Integer.toString(getNextMsgId());
        gcm.send(GarageDoorWidgetProvider.GCM_SENDER_ID + "@gcm.googleapis.com",
                id, TIME_TO_LIVE, data);
    } catch (IOException e) {
        Log.e(TAG, "Error sending message", e);
    }
}
 
Example 7
Project: GarageDoor   File: RegistrationIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    try {
        InstanceID instanceID = InstanceID.getInstance(this);
        String token = instanceID.getToken(GarageDoorWidgetProvider.GCM_SENDER_ID,
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        Log.i(TAG, "GCM Registration Token: " + token);

        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(GarageDoorWidgetProvider.PREF_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(GarageDoorWidgetProvider.PREF_SENT_TOKEN_TO_SERVER, false).apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(GarageDoorWidgetProvider.PREF_REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
 
Example 8
Project: Android_watch_magpie   File: RegistrationIntentService.java   Source Code and License 6 votes vote down vote up
@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_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            Log.i(TAG, "GCM Registration Token: " + token);
            sharedPreferences.edit().putString(Preferences.TOKEN, token).apply();
        }
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        //sharedPreferences.edit().putBoolean(Preferences.SENT_TOKEN_TO_SERVER, false).apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent(Preferences.REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
 
Example 9
Project: stitch-android-sdk   File: GCMPushClient.java   Source Code and License 6 votes vote down vote up
/**
 * Deletes the current registration token.
 *
 * @param instanceId The instance ID which generated the registration token.
 * @param senderId   The sender ID to revoke the registration token from.
 * @return A task that can be resolved upon deletion of the token.
 */
private Task<Void> deleteRegistrationToken(final InstanceID instanceId, final String senderId) {
    final TaskCompletionSource<Void> future = new TaskCompletionSource<>();
    new AsyncTask<Object, Integer, String>() {
        @Override
        protected String doInBackground(final Object[] ignored) {

            try {
                instanceId.deleteToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE);
            } catch (final IOException e) {
                Log.e(TAG, "Error deleting GCM registration token", e);
                future.setException(e);
                return null;
            }

            future.setResult(null);
            return null;
        }
    }.execute();

    return future.getTask();
}
 
Example 10
Project: stitch-android-sdk   File: GCMPushClient.java   Source Code and License 6 votes vote down vote up
/**
 * Gets or creates a registration token.
 *
 * @param instanceId The instance ID which should generate the registration token.
 * @param senderId   The sender ID to generate the registration token for.
 * @return A task that can be resolved upon creating/retrieval of the token.
 */
private Task<String> getRegistrationToken(final InstanceID instanceId, final String senderId) {
    final TaskCompletionSource<String> future = new TaskCompletionSource<>();
    new AsyncTask<Object, Integer, String>() {
        @Override
        protected String doInBackground(final Object[] ignored) {

            final String registrationToken;
            try {
                registrationToken = instanceId.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE);
            } catch (final IOException e) {
                Log.e(TAG, "Error getting GCM registration token", e);
                future.setException(e);
                return null;
            }

            future.setResult(registrationToken);
            return null;
        }
    }.execute();

    return future.getTask();
}
 
Example 11
Project: financisto1-holo   File: GCMIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);
    if (!extras.isEmpty()) {
    	if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {	    		
    		if (FlowzrSyncEngine.isRunning) {
     		Log.i(TAG,"sync already in progess");
    			return;
    		}
    		Log.i(TAG,"starting sync from GCM");
    		new FlowzrSyncTask(getApplicationContext()).execute();
        }
    }
}
 
Example 12
Project: android-gcm-client-demo   File: RegistrationIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {

    String deviceId = intent.getStringExtra("DEVICE_ID");
    String deviceName = intent.getStringExtra("DEVICE_NAME");

    try {
        InstanceID instanceID = InstanceID.getInstance(this);
        String registrationId = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        registerDeviceProcess(deviceName,deviceId,registrationId);

    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example 13
Project: GYAppAnd   File: PushNotificationIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);

    Log.w("PushIntentSerivce", extras.toString());

    if (!extras.isEmpty()) {
        String from = extras.getString("from");

        if (!from.equals("google.com/iid") && GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            createNotification(extras);
        }
    }

    PushNotificationBroadcastReceiver.completeWakefulIntent(intent);
}
 
Example 14
Project: Android-SDK   File: InteractionRegistration.java   Source Code and License 6 votes vote down vote up
@Override
public void interaction() {
    gcm = GoogleCloudMessaging.getInstance(context);
    if(operationStatus() != StaticFields.STATUS_OK)
    {
        mJobSheduler = new MJobSheduler(this);
        timer = new Timer(true);
        timer.schedule(mJobSheduler, 1000, 1000);
    }
    else
    {
       if (nextChain != null)
       {
           nextChain.setSocket(tcpChannel,nextChain.msgHandler);
           nextChain.getDataObject().setPushToken(FileUtil.getPushToken(context));
           nextChain.interaction();
       }
    }
}
 
Example 15
Project: Asynchronous-Android-Programming   File: MyBackupService.java   Source Code and License 6 votes vote down vote up
@Override
public int onRunTask(TaskParams taskParams) {
    Log.i(TAG, "Backing up the account settings");

    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    Bundle data = new Bundle();
    data.putString(FIRST_NAME, sharedPreferences.getString(FIRST_NAME,""));
    data.putString(LAST_NAME, sharedPreferences.getString(LAST_NAME,""));
    data.putString(AGE, sharedPreferences.getString(AGE,""));
    data.putString("resource", RESOURCE);
    data.putString("operation", sharedPreferences.getString(OPERATION,""));
    String id = Integer.toString(new Random().nextInt());
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(MyBackupService.this);
    try {
        gcm.send(getString(R.string.gcm_SenderId) + "@gcm.googleapis.com", id, data);
    } catch (IOException e) {
        Log.e(TAG, "Failed to backup account");
        return GcmNetworkManager.RESULT_RESCHEDULE;
    }


    return GcmNetworkManager.RESULT_SUCCESS;
}
 
Example 16
Project: gcm-android   File: RegistrationIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    // Preferences to get registration id from device
    SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    String mNextId = mSharedPreferences.getString(REGISTRATION_ID_PREFERENCE, null);
    try {
        InstanceID mInstanceID = InstanceID.getInstance(this);
        String mToken = mInstanceID.getToken(getString(R.string.gcm_default_sender_id),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            executeBusinessRule(mToken);

        if(mNextId!=null && mNextId!=mToken) {
            mSharedPreferences.edit().putString(REGISTRATION_ID_PREFERENCE, mToken).apply();
            mNextId = mToken;
        }

    } catch (Exception e) {
        Log.d(REGISTRATION_DEBUG, "Failed to refresh current token: " + e.getMessage());
    }

    // Complete process
    if(mNextId!=null) {
        Intent mRegisterIntent = new Intent(REGISTRATION_COMPLETE);
        LocalBroadcastManager.getInstance(this).sendBroadcast(mRegisterIntent);
    }
}
 
Example 17
Project: PushEZ   File: GcmIntentService.java   Source Code and License 6 votes vote down vote up
/**
 * Subscribe to a topic
 */
public void subscribeToTopic(String topic) {
    GcmPubSub pubSub = GcmPubSub.getInstance(getApplicationContext());
    InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
    String token = null;
    String gcm_server_sender_id = SharedPref.getSenderId(GcmIntentService.this);
    try {
        token = instanceID.getToken(gcm_server_sender_id,
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        if (token != null) {
            pubSub.subscribe(token, "/topics/" + topic, null);
            Log.d(TAG, "Subscribed to topic: " + topic);
        } else {
            Log.d(TAG, "error: gcm registration id is null");
        }
    } catch (IOException e) {
        Log.e(TAG, "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage());
        Toast.makeText(getApplicationContext(), "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
 
Example 18
Project: librus-client   File: RegistrationIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    boolean register = intent.getBooleanExtra(LibrusConstants.REGISTER, false);
    try {
        if (register) {
            String token = InstanceID.getInstance(this)
                    .getToken(APP_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            LibrusUtils.log("Retrieved GCM token " + token);
            new APIClient(this).pushDevices(token)
                    .subscribe(() -> {
                    }, LibrusUtils::handleError);
        } else {
            InstanceID.getInstance(this)
                    .deleteToken(APP_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE);
            LibrusUtils.log("Unregistered GCM");
        }
    } catch (IOException e) {
        LibrusUtils.logError("Failed to register GCM");
        FirebaseCrash.report(e);
        e.printStackTrace();
    }
}
 
Example 19
Project: Popdeem-SDK-Android   File: GCMIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    PDLog.d(GCMIntentService.class, "onHandleIntent");
    if (intent == null) {
        return;
    }

    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);
    Bundle extras = intent.getExtras();

    if (!extras.isEmpty() && messageType.equalsIgnoreCase(GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE)) {
        handleMessage(intent);
    }

    GCMBroadcastReceiver.completeWakefulIntent(intent);
}
 
Example 20
Project: VKAudioSave   File: RegistrationIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    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);
        subscribeTopics(token);
        sharedPreferences.edit().putString(QuickstartPreferences.TOKEN, token).apply();
        sharedPreferences.edit().putBoolean(ml.hepolise.vkaudiosave.QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        sharedPreferences.edit().putBoolean(ml.hepolise.vkaudiosave.QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
    }
    Intent registrationComplete = new Intent(ml.hepolise.vkaudiosave.QuickstartPreferences.REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
 
Example 21
Project: android-oss   File: UnregisterService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(final @NonNull Intent intent) {
  Timber.d("onHandleIntent");

  try {
    final InstanceID instanceID = InstanceID.getInstance(this);
    instanceID.deleteToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE);
    Timber.d("Deleted token");
  } catch (final Exception e) {
    Timber.e("Failed to delete token: %s", e);
  }
}
 
Example 22
Project: android-oss   File: RegisterService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(final @Nullable Intent intent) {
  Timber.d("onHandleIntent");

  try {
    // This initially hits the network to retrieve the token, subsequent calls are local
    final InstanceID instanceID = InstanceID.getInstance(this);

    // R.string.gcm_defaultSenderId is derived from google-services.json
    final String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
      GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
    Timber.d("Token: %s", token);

    sendTokenToApi(token);
    subscribeToGlobalTopic(token);
  } catch (final Exception e) {
    Timber.e("Failed to complete token refresh: %s", e);
  }
}
 
Example 23
Project: TextSecure   File: ApplicationPreferencesActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected Integer doInBackground(Void... params) {
  try {
    Context                  context        = getActivity();
    TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(context);

    accountManager.setGcmId(Optional.<String>absent());
    GoogleCloudMessaging.getInstance(context).unregister();

    return SUCCESS;
  } catch (AuthorizationFailedException afe) {
    Log.w(TAG, afe);
    return SUCCESS;
  } catch (IOException ioe) {
    Log.w(TAG, ioe);
    return NETWORK_ERROR;
  }
}
 
Example 24
Project: TextSecure   File: RegistrationService.java   Source Code and License 6 votes vote down vote up
private void handleCommonRegistration(MasterSecret masterSecret, TextSecureAccountManager accountManager, String number)
    throws IOException
{
  setState(new RegistrationState(RegistrationState.STATE_GENERATING_KEYS, number));
  IdentityKeyPair    identityKey  = IdentityKeyUtil.getIdentityKeyPair(this, masterSecret);
  List<PreKeyRecord> records      = PreKeyUtil.generatePreKeys(this, masterSecret);
  PreKeyRecord       lastResort   = PreKeyUtil.generateLastResortKey(this, masterSecret);
  SignedPreKeyRecord signedPreKey = PreKeyUtil.generateSignedPreKey(this, masterSecret, identityKey);
  accountManager.setPreKeys(identityKey.getPublicKey(),lastResort, signedPreKey, records);

  setState(new RegistrationState(RegistrationState.STATE_GCM_REGISTERING, number));

  String gcmRegistrationId = GoogleCloudMessaging.getInstance(this).register(GcmRefreshJob.REGISTRATION_ID);
  TextSecurePreferences.setGcmRegistrationId(this, gcmRegistrationId);
  accountManager.setGcmId(Optional.of(gcmRegistrationId));

  DirectoryHelper.refreshDirectory(this, accountManager, number);

  DirectoryRefreshListener.schedule(this);
}
 
Example 25
Project: TextSecure   File: GcmRefreshJob.java   Source Code and License 6 votes vote down vote up
@Override
public void onRun() throws Exception {
  TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(context);
  String                   registrationId = TextSecurePreferences.getGcmRegistrationId(context);

  if (registrationId == null) {
    Log.w(TAG, "GCM registrationId expired, reregistering...");
    int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);

    if (result != ConnectionResult.SUCCESS) {
      notifyGcmFailure();
    } else {
      String gcmId = GoogleCloudMessaging.getInstance(context).register(REGISTRATION_ID);
      accountManager.setGcmId(Optional.of(gcmId));
      TextSecurePreferences.setGcmRegistrationId(context, gcmId);
    }
  }
}
 
Example 26
Project: TextSecure   File: GcmBroadcastReceiver.java   Source Code and License 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
  GoogleCloudMessaging gcm         = GoogleCloudMessaging.getInstance(context);
  String               messageType = gcm.getMessageType(intent);

  if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
    Log.w(TAG, "GCM message...");

    if (!TextSecurePreferences.isPushRegistered(context)) {
      Log.w(TAG, "Not push registered!");
      return;
    }

    String messageData = intent.getStringExtra("message");
    String receiptData = intent.getStringExtra("receipt");

    if      (!TextUtils.isEmpty(messageData)) handleReceivedMessage(context, messageData);
    else if (!TextUtils.isEmpty(receiptData)) handleReceivedMessage(context, receiptData);
  }
}
 
Example 27
Project: mattermost-android-classic   File: RegistrationIntentService.java   Source Code and License 6 votes vote down vote up
@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 28
Project: dasher-app-android   File: RegistrationIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    // Make a call to Instance API
    InstanceID instanceID = InstanceID.getInstance(this);
    String senderId = getResources().getString(R.string.gcm_defaultSenderId);
    try {
        // request token that will be used by the server to send push notifications
        String token = instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE);

        // pass along this data
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        sharedPreferences.edit().putString(GCM_TOKEN, token).apply();

        sendRegistrationToServer(token);

    } catch (IOException e) {}
}
 
Example 29
Project: mobile-messaging-sdk-android   File: RegistrationTokenHandler.java   Source Code and License 6 votes vote down vote up
void handleRegistrationTokenUpdate(Context context) {
    String senderId = MobileMessagingCore.getGcmSenderId(context);
    if (StringUtils.isBlank(senderId)) {
        return;
    }

    try {
        InstanceID instanceID = InstanceID.getInstance(context);
        String token = instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        MobileMessagingLogger.v(MobileMessagingLogger.TAG, "RECEIVED TOKEN", token);
        new AndroidBroadcaster(context).registrationAcquired(token);
        sendRegistrationToServer(context, token);
        subscribeTopics(context, token);
    } catch (IOException e) {
        MobileMessagingLogger.e(InternalSdkError.ERROR_TOKEN_REFRESH.get(), e);
    }
}
 
Example 30
Project: findlunch   File: GcmRegistrationIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {

    try {
        // Retrieve the GCM-Token
        InstanceID instanceID = InstanceID.getInstance(this);
        String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

        // Broadcasts the GCM-Token as a Message (so it can be used by other classes).
        sendGcmTokenMessage(true, token);

    } catch (Exception e) {
        Log.w("GcmRegistration", "GCM Token could not be obtained");
        sendGcmTokenMessage(false, "");
    }
}
 
Example 31
Project: EmbeddedSocial-Android-SDK   File: GetGcmIdHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void handleIntent(ServiceAction action, Intent intent) {
	if (!tokenHolder.hasValidToken()) {
		DebugLog.i("obtaining new GCM token");
		InstanceID instanceID = InstanceID.getInstance(context);
		try {
			String token = instanceID.getToken(
				context.getString(R.string.gcm_defaultSenderId),
				GoogleCloudMessaging.INSTANCE_ID_SCOPE,
				null
			);
			GcmTokenHolder.create(context).storeToken(token);
			DebugLog.i("GCM token obtained successfully");
		} catch (IOException e) {
			DebugLog.logException(e);
		}
	}
	WorkerService.getLauncher(context).launchService(ServiceAction.SYNC_DATA);
}
 
Example 32
Project: ti.goosh   File: TiGooshModule.java   Source Code and License 6 votes vote down vote up
@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 33
Project: ti.goosh   File: RegistrationIntentService.java   Source Code and License 6 votes vote down vote up
@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 34
Project: whereuat-android   File: RegistrationIntentService.java   Source Code and License 6 votes vote down vote up
/**
 * This method receives an intent from the system when a GCM token is received.
 *
 * @param intent an Intent containing the GCM token for the application to use
 */
@Override
protected void onHandleIntent(Intent intent) {

    String token = "";
    try {
        // 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.
        InstanceID instanceID = InstanceID.getInstance(this);
        token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
    }
    // Broadcast the token to the login activity so the account can be created on the [email protected]
    // server.
    Intent registrationComplete = new Intent(Constants.TOKEN_BROADCAST);
    registrationComplete.putExtra(Constants.TOKEN_EXTRA, token);
    // Unique broadcast ID to prevent broadcast receiver from receiving the same broadcast twice
    registrationComplete.putExtra(Constants.TOKEN_BROADCAST_ID_EXTRA,
            new Random().nextInt(Integer.MAX_VALUE));
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
 
Example 35
Project: Vafrinn   File: InvalidationGcmUpstreamSender.java   Source Code and License 6 votes vote down vote up
private void sendUpstreamMessage(String to, Bundle data, String token) {
    if (token == null) {
        GcmUpstreamUma.recordHistogram(
                getApplicationContext(), GcmUpstreamUma.UMA_TOKEN_REQUEST_FAILED);
    }
    // Add the OAuth2 token to the bundle. The token should have the prefix Bearer added to it.
    data.putString("Authorization", "Bearer " + token);
    if (!isMessageWithinLimit(data)) {
        GcmUpstreamUma.recordHistogram(
                getApplicationContext(), GcmUpstreamUma.UMA_SIZE_LIMIT_EXCEEDED);
        return;
    }
    String msgId = UUID.randomUUID().toString();
    try {
        GoogleCloudMessaging.getInstance(getApplicationContext()).send(to, msgId, 1, data);
    } catch (IOException | IllegalArgumentException exception) {
        Log.w(TAG, "Send message failed");
        GcmUpstreamUma.recordHistogram(getApplicationContext(), GcmUpstreamUma.UMA_SEND_FAILED);
    }
}
 
Example 36
Project: react-native-notifications   File: GcmToken.java   Source Code and License 6 votes vote down vote up
@NonNull
protected String getNewToken() throws Exception {
    final InstanceID instanceId = InstanceID.getInstance(mAppContext);
    Log.d(LOGTAG, "GCM is refreshing token... instanceId=" + instanceId.getId());

    // TODO why is this needed?
    GoogleCloudMessaging.getInstance(mAppContext).close();

    try {
        final String registrationToken = instanceId.getToken(getSenderId(), GoogleCloudMessaging.INSTANCE_ID_SCOPE);
        Log.i(LOGTAG, "GCM has a new token: instanceId=" + instanceId.getId() + ", token=" + registrationToken);
        return registrationToken;
    } catch (Exception e) {
        throw new Exception("FATAL: Failed to fetch a fresh new token, instanceId=" + instanceId.getId(), e);
    }
}
 
Example 37
Project: Rocket.Chat-android   File: RocketRegistrationIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    mRxMethods = ((RocketApp)getApplicationContext()).getRxMethods();
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    try {

        InstanceID instanceID = InstanceID.getInstance(this);
        String senderId = mSharedPreferences.getString(PushKeys.SENDER_ID, null);
        String token = instanceID.getToken(senderId,
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

        sendRegistrationToServer(token);

        subscribeTopics(token);


        mSharedPreferences.edit().putString(PushKeys.TOKEN, token).apply();

    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        mSharedPreferences.edit().putBoolean(PushKeys.SENT_TOKEN_TO_SERVER, false).apply();
    }
}
 
Example 38
Project: fablab-android   File: PushModel.java   Source Code and License 6 votes vote down vote up
private void unregisterInBackground() {
    new AsyncTask<Context, Void, Void>() {
        @Override
        protected Void doInBackground(Context... params) {
            try {
                GoogleCloudMessaging mGoogleCloudMessaging = GoogleCloudMessaging.getInstance(
                        params[0]);
                mGoogleCloudMessaging.unregister();
                Log.i(TAG, "Device unregistered");
            } catch (IOException e) {
                Log.i(TAG, "Error", e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            deleteRegistrationIdFromBackend();
            deleteRegistrationId();
            mPushId = "0";
        }
    }.execute(mContext);
}
 
Example 39
Project: fme-apps-android   File: GCMIntentService.java   Source Code and License 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
   Bundle extras = intent.getExtras();
   GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
   String messageType = gcm.getMessageType(intent);
   if(!extras.isEmpty()){
      if(GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)){
         Log.i("GCMIntentService", "Received message");
         String details = intent.getStringExtra( "alert" ) ;
         String title = intent.getStringExtra( "title" ) ;
         String[] location = parseLocation(intent.getStringExtra("location"));
         addAlert(title, details, location[1],location[0]);
         generateNotification(this,title, details,location[1],location[0]);
      }
   }
   GCMBroadcastReceiver.completeWakefulIntent(intent);
}
 
Example 40
Project: KanJuice   File: GCMRegistrationIntentService.java   Source Code and License 6 votes vote down vote up
public void registerToGCM() {

        Intent registrationComplete;
        String token = null;
        try {
            InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
            logger.d("senderId is :" + getString(R.string.senderId));
            token = instanceID.getToken(getString(R.string.senderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            logger.d("GCMIntentService token : " + token);
            registrationComplete = new Intent(REGISTRATION_SUCESS);
            registrationComplete.putExtra("token", token);

        } catch (Exception e) {
            registrationComplete = new Intent(REGISTRATION_FAILD);
            logger.e("GCMIntentService registration failed " + token);
        }
        //send broadcast
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }