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

The following examples show how to use com.google.android.gms.gcm.GoogleCloudMessaging. 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: MainActivity.java    From evercam-android with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (isPlayServicesAvailable()) {
            gcm = GoogleCloudMessaging.getInstance(this);
            registrationId = PrefsManager.getGcmRegistrationId(this);
            if (registrationId.isEmpty()) {
                registerInBackground();
            } else {
                sendRegistrationIdToIntercomBackend(registrationId);
            }
        } else {
            Log.i(TAG, "Google Play Services is not available");
        }

//        Fabric.with(this, new Crashlytics());

        setContentView(R.layout.activity_main);

        launch();
    }
 
Example #2
Source File: RegistrationIntentService.java    From httpebble-android with MIT License 6 votes vote down vote up
@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: MainActivity.java    From effective_android_sample with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    Button btnRegist = (Button) findViewById(R.id.btn_regist);
    btnRegist.setOnClickListener(this);
    Button btnUnregist = (Button) findViewById(R.id.btn_unregist);
    btnUnregist.setOnClickListener(this);
    
    context = getApplicationContext();
    
    // デバイスにPlayサービスAPKが入っているか検証する
    if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(context);
        regid = getRegistrationId(context);
    } else {
        Log.i(TAG, "Google Play Services APKが見つかりません");
    }
}
 
Example #4
Source File: CbService.java    From PressureNet-SDK with MIT License 6 votes vote down vote up
/** 
 * Send registration info to GCM for notifications
 */
private void registerForNotifications() {
	log("cbservice registering for notifications");
	gcm = GoogleCloudMessaging.getInstance(getBaseContext());
	 new AsyncTask(){
            protected Object doInBackground(final Object... params) {
            	log("cbservice running asynctask to register for notifications");
                String token;
                try {
                    token = gcm.register(CbConfiguration.API_PROJECT_NUMBER);
                    log("registrationId " + token);
                    sendRegistrationToServer(token);
                } 
                catch (IOException e) {
                    log("registration rrror " + e.getMessage());
                }
                return true;
            }
        }.execute(null, null, null);
}
 
Example #5
Source File: GCMIntentService.java    From gsn with GNU General Public License v3.0 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_SEND_ERROR.equals(messageType)) {
			sendNotification("Send error: " + extras.toString());
		} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
			sendNotification("Deleted messages on server: "
					+ extras.toString());
		} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

			sendNotification("Message Received from Google GCM Server: "  + extras.get(CommonUtilities.EXTRA_MESSAGE));
			Log.i(TAG, "Received: " + extras.toString());
		}
	}
	GCMBroadcastReceiver.completeWakefulIntent(intent);
}
 
Example #6
Source File: GCMIntentService.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
private static String doRegister(Context context) {
    String msg = "";
    try {
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
        String regId = gcm.register(Consts.PROJECT_NUMBER);
        msg = "Device registered, registration ID=" + regId;

        // For this demo: we don't need to send it because the device will send
        // upstream messages to a server that echo back the message using the
        // 'from' address in the message.

        SharedPreferences prefs = getGcmPreferences(context);
        int appVersion = getAppVersion(context);
        Log.i(Consts.TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        editor.commit();
    } catch (IOException ex) {
        msg = "Error :" + ex.getMessage();
        // If there is an error, don't just keep trying to register.
        // Require the user to click a button again, or perform
        // exponential back-off.
    }
    return msg;
}
 
Example #7
Source File: RegistrationIntentService.java    From mattermost-android-classic with Apache License 2.0 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 #8
Source File: GCMUtils.java    From buddycloud-android with Apache License 2.0 6 votes vote down vote up
/**
 * This method unregister from the GCM services and also pusher
 * server in the background mode. 
 * 
 * @param context
 */
public static void unregisterInBackground(final Context context) {
	
	new AsyncTask<Void, Void, String>() {

		@Override
		protected String doInBackground(Void... params) {

			try {
				GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
				gcm.unregister();
				
				// Unregister the GCM info from pusher server.
				String regId = Preferences.getPreference(context, Preferences.CURRENT_GCM_ID);
				GCMIntentService.removeFromPusher(context, regId);
			} catch (IOException e) {
				Logger.error(TAG, "GCM Un-registration failed.", e);
			} 
			
			return null;
		}
	}.execute();
}
 
Example #9
Source File: GCMReceiver.java    From tapchat-android with Apache License 2.0 6 votes vote down vote up
@Override public void onReceive(Context context, Intent intent) {
    String messageType = mGCM.getMessageType(intent);
    if (!messageType.equals(GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE)) {
        return;
    }

    try {
        byte[] cipherText = Base64.decode(intent.getStringExtra("payload"), Base64.URL_SAFE | Base64.NO_WRAP);
        byte[] iv = Base64.decode(intent.getStringExtra("iv"), Base64.URL_SAFE | Base64.NO_WRAP);

        byte[] key = mPusherClient.getPushKey();
        if (key == null) {
            // I don't think this will ever happen
            throw new Exception("Received push notification before receiving decryption key.");
        }

        JSONObject message = new JSONObject(new String(decrypt(cipherText, key, iv), "UTF-8"));

        Intent broadcastIntent = new Intent(TapchatApp.ACTION_MESSAGE_NOTIFY);
        addExtras(broadcastIntent, message);
        context.sendOrderedBroadcast(broadcastIntent, null);
    } catch (Exception ex) {
        Log.e(TAG, "Error parsing push notification", ex);
    }
}
 
Example #10
Source File: GCMManager.java    From Mobilyzer with Apache License 2.0 6 votes vote down vote up
public GCMManager(Context context) {
 this.context=context;
 // Check device for Play Services APK. If check succeeds, proceed with GCM registration.
 if (checkPlayServices()) {
     gcm = GoogleCloudMessaging.getInstance(context);
     regid = getRegistrationId();
     Logger.d("GCMManager: regid = "+regid);

     if (regid.isEmpty()) {
         registerInBackground();
     }
 } else {
     Logger.e("GCMManager: No valid Google Play Services APK found.");
 }

}
 
Example #11
Source File: TiGooshModule.java    From ti.goosh with MIT 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 #12
Source File: RegistrationIntentService.java    From ti.goosh with MIT 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 #13
Source File: GCMProvider.java    From OPFPush with Apache License 2.0 6 votes vote down vote up
@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 #14
Source File: SendMessageService.java    From OPFPush with Apache License 2.0 6 votes vote down vote up
@Override
protected void onHandleIntent(final Intent intent) {
    OPFLog.logMethod(OPFUtils.toString(intent));

    if (ACTION_SEND_MESSAGE.equals(intent.getAction())) {
        final Message message = intent.getParcelableExtra(EXTRA_MESSAGE);
        final String messageTo = intent.getStringExtra(EXTRA_MESSAGES_TO);

        try {
            GoogleCloudMessaging.getInstance(this).send(
                    messageTo,
                    message.getId(),
                    message.getTimeToLeave(),
                    message.getData()
            );
            OPFLog.d("Message '%s' has sent.", message);
        } catch (IOException ex) {
            OPFLog.e(String.format("Error while send Message '%s'.", message), ex);
        }
    } else {
        OPFLog.w("Unknown action '%s'.", intent.getAction());
    }
}
 
Example #15
Source File: FriendlyPingFragment.java    From friendlyping with Apache License 2.0 6 votes vote down vote up
/**
 * Ping another registered client
 */
private void pingSomeone(Pinger pinger) {
    final Context context = getActivity();
    Bundle data = new Bundle();
    data.putString(PingerKeys.ACTION, GcmAction.PING_CLIENT);
    data.putString(PingerKeys.TO, pinger.getRegistrationToken());
    data.putString(PingerKeys.SENDER,
            mDefaultSharedPreferences.getString(RegistrationConstants.TOKEN, null));
    try {
        GoogleCloudMessaging.getInstance(context)
                .send(FriendlyPingUtil.getServerUrl(getActivity()),
                        String.valueOf(System.currentTimeMillis()), data);
        AnalyticsHelper.send(context, TrackingEvent.PING_SENT);
    } catch (IOException e) {
        Log.w(TAG, "Could not ping client.", e);
    }
    mPingerAdapter.moveToTop(pinger);
}
 
Example #16
Source File: MessageSenderService.java    From easygoogle with Apache License 2.0 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        String senderEmail = getSenderEmail(intent.getStringExtra(MessagingFragment.SENDER_ID_ARG));
        Bundle data = intent.getBundleExtra(MessagingFragment.MESSAGE_ARG);
        String id = Integer.toString(sMessageId.incrementAndGet());
        Log.d(TAG, "Sending gcm message:" + senderEmail + ":" + data + ":" + id);

        try {
            GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
            gcm.send(senderEmail, id, data);
            Log.d(TAG, "Sent!");
        } catch (IOException e) {
            Log.e(TAG, "Failed to send GCM Message.", e);
        }
    }
}
 
Example #17
Source File: IIDService.java    From BackPackTrackII with GNU General Public License v3.0 6 votes vote down vote up
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 #18
Source File: MainActivity.java    From MobileShoppingAssistant-sample with Apache License 2.0 6 votes vote down vote up
@Override
protected String doInBackground(final Void... params) {
    String msg;
    try {
        if (gcm == null) {
            gcm = GoogleCloudMessaging.getInstance(context);
        }
        regId = gcm.register(Constants.SENDER_ID);
        msg = String.format(
                getString(R.string.gcmRegistrationSuccess), regId);

        sendRegistrationIdToBackend();
    } catch (IOException ex) {
        LOG.warning("Exception when registering device with GCM ="
                + ex.getMessage());
        // If there is an error, we will try again to register the
        // device with GCM the next time the MainActivity starts.
        msg = getString(R.string.gcmRegistrationError);
    }
    return msg;
}
 
Example #19
Source File: GCMProvider.java    From OPFPush with Apache License 2.0 5 votes vote down vote up
@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 #20
Source File: GPPRegistrationIntentService.java    From GCMPushPlugin with MIT License 5 votes vote down vote up
@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 #21
Source File: MainActivity.java    From evercam-android with GNU Affero General Public License v3.0 5 votes vote down vote up
private void registerInBackground() {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
                }
                registrationId = gcm.register(GCM_SENDER_ID);

                sendRegistrationIdToIntercomBackend(registrationId);
                PrefsManager.storeGcmRegistrationId(getApplicationContext(), registrationId);
                Log.d("GCM_SUCCESS", "Current Device's Registration ID is: " + msg);
            } catch (IOException ex) {
                Log.d("GCM_ISSUE", "Error :" + ex.getMessage());
                //retry the registration after delay
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                registerInBackground();
                            }
                        }, retryTime);
                        //increase the time of wait period
                        if (retryTime < MAX_RETRY) {
                            retryTime *= 2;
                        }
                    }
                });
            }
            return null;
        }
    }.execute(null, null, null);
}
 
Example #22
Source File: GcmIntentService.java    From Mobilyzer with Apache License 2.0 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
  Bundle extras = intent.getExtras();
  GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
  // The getMessageType() intent parameter must be the intent you received
  // in your BroadcastReceiver.
  String messageType = gcm.getMessageType(intent);

  if (!extras.isEmpty()) { // has effect of unparcelling Bundle
    /*
     * Filter messages based on message type. Since it is likely that GCM will be extended in the
     * future with new message types, just ignore any message types you're not interested in, or
     * that you don't recognize.
     */
    if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
      Logger.d("GCMManager -> GcmIntentService -> MESSAGE_TYPE_SEND_ERROR");
    } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
      Logger.d("GCMManager -> GcmIntentService -> MESSAGE_TYPE_DELETED");
    } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
      Logger.d("GCMManager -> MESSAGE_TYPE_MESSAGE -> " + extras.toString());
      if (extras.containsKey("task")) {
        Logger.d("GCMManager -> " + extras.getString("task"));
        
        Intent newintent = new Intent();
        newintent.setAction(UpdateIntent.GCM_MEASUREMENT_ACTION);
        newintent.putExtra(UpdateIntent.MEASUREMENT_TASK_PAYLOAD, extras.getString("task"));
        sendBroadcast(newintent);

      }
    }
  }
  // Release the wake lock provided by the WakefulBroadcastReceiver.
  GcmBroadcastReceiver.completeWakefulIntent(intent);
}
 
Example #23
Source File: GCMManager.java    From Mobilyzer with Apache License 2.0 5 votes vote down vote up
/**
 * Registers the application with GCM servers asynchronously.
 * <p>
 * Stores the registration ID and the app versionCode in the application's
 * shared preferences.
 */
private void registerInBackground() {
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                Logger.d("GCMManager: regid: "+regid);
                msg = "Device registered, registration ID=" + regid;

                // Persist the regID - no need to register again.
                storeRegistrationId(context, regid);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
                // If there is an error, don't just keep trying to register.
                // Require the user to click a button again, or perform
                // exponential back-off.
            }
            return msg;
        }

        
    }.execute(null, null, null);
}
 
Example #24
Source File: GCMIntentService.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that GCM will be
         * extended in the future with new message types, just ignore any message types you're
         * not interested in, or that you don't recognize.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            Log.i(Consts.TAG, "onHandleIntent: message error");
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            Log.i(Consts.TAG, "onHandleIntent: message deleted");
        // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            String subId = intent.getStringExtra(GCM_KEY_SUBID);
            Log.i(Consts.TAG, "onHandleIntent: subId: " + subId);
            String[] tokens = subId.split(":");
            String typeId = tokens[1];

            // dispatch message
            if (GCM_TYPEID_QUERY.equals(typeId)) {
                Intent messageIntent = new Intent(BROADCAST_ON_MESSAGE);
                messageIntent.putExtras(intent);
                messageIntent.putExtra("token", tokens[2]);
                LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
            }
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GCMBroadcastReceiver.completeWakefulIntent(intent);
}
 
Example #25
Source File: IDRegisterService.java    From easygoogle with Apache License 2.0 5 votes vote down vote up
@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 #26
Source File: GCMRegistration.java    From redalert-android with Apache License 2.0 5 votes vote down vote up
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 #27
Source File: GcmIntentService.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 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)) {
        String rawJson = extras.getString("message");

        try {
            JSONObject Msg = new JSONObject(rawJson);
            JSONObject Srv = Msg.getJSONObject("service");
            PushfishService srv = new PushfishService(
                    Srv.getString("public"),
                    Srv.getString("name"),
                    new Date((long) Srv.getInt("created") * 1000)
            );
            srv.setIcon(Srv.getString("icon"));

            PushfishMessage msg = new PushfishMessage(
                    srv,
                    Msg.getString("message"),
                    Msg.getString("title"),
                    Msg.getInt("timestamp")
            );
            msg.setLevel(Msg.getInt("level"));
            msg.setLink(Msg.getString("link"));
            DatabaseHandler db = new DatabaseHandler(this);
            db.addMessage(msg);
            sendNotification(msg);
        } catch (JSONException ignore) {
            Log.e("PushfishJson", ignore.getMessage());
        }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
    sendBroadcast(new Intent("PushfishMessageRefresh"));
}
 
Example #28
Source File: PushReceiver.java    From actor-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
    Bundle extras = intent.getExtras();
    String messageType = gcm.getMessageType(intent);
    if (!extras.isEmpty()) {
        if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            ActorSDK.sharedActor().waitForReady();
            if (extras.containsKey("seq")) {
                int seq = Integer.parseInt(extras.getString("seq"));
                int authId = Integer.parseInt(extras.getString("authId", "0"));
                Log.d(TAG, "Push received #" + seq);
                ActorSDK.sharedActor().getMessenger().onPushReceived(seq, authId);
                setResultCode(Activity.RESULT_OK);
            } else if (extras.containsKey("callId")) {
                long callId = Long.parseLong(extras.getString("callId"));
                int attempt = 0;
                if (extras.containsKey("attemptIndex")) {
                    attempt = Integer.parseInt(extras.getString("attemptIndex"));
                }
                Log.d(TAG, "Received Call #" + callId + " (" + attempt + ")");
                ActorSDK.sharedActor().getMessenger().checkCall(callId, attempt);
                setResultCode(Activity.RESULT_OK);
            }
        }
    }
    WakefulBroadcastReceiver.completeWakefulIntent(intent);
}
 
Example #29
Source File: PushManager.java    From actor-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
private String tryRegisterPush(Context context) {
    GoogleCloudMessaging cloudMessaging = GoogleCloudMessaging.getInstance(context);
    Log.d(TAG, "Requesting push token iteration...");
    try {
        return cloudMessaging.register("" + ActorSDK.sharedActor().getPushId());
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #30
Source File: GCMModule.java    From gcmpush with Apache License 2.0 5 votes vote down vote up
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;
    }
}