Java Code Examples for com.google.android.gms.gcm.GoogleCloudMessaging#getInstance()

The following examples show how to use com.google.android.gms.gcm.GoogleCloudMessaging#getInstance() . 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 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 2
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 3
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 4
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 5
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 6
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 7
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 8
Source File: GcmIntentService.java    From Pushjet-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)) {
        try {
            JSONObject AzMsg = new JSONObject(extras.getString("message"));
            JSONObject AzServ = AzMsg.getJSONObject("service");
            PushjetService srv = new PushjetService(
                    AzServ.getString("public"),
                    AzServ.getString("name"),
                    new Date((long) AzServ.getInt("created") * 1000)
            );
            srv.setIcon(AzServ.getString("icon"));

            PushjetMessage msg = new PushjetMessage(
                    srv,
                    AzMsg.getString("message"),
                    AzMsg.getString("title"),
                    AzMsg.getInt("timestamp")
            );
            msg.setLevel(AzMsg.getInt("level"));
            msg.setLink(AzMsg.getString("link"));
            DatabaseHandler db = new DatabaseHandler(this);
            db.addMessage(msg);
            sendNotification(msg);
        } catch (JSONException ignore) {
            Log.e("PushjetJson", ignore.getMessage());
        }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
    sendBroadcast(new Intent("PushjetMessageRefresh"));
}
 
Example 9
Source File: Notifications.java    From zulip-android with Apache License 2.0 5 votes vote down vote up
public void register() {
    if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(app);
        regid = getRegistrationId();

        if (regid.isEmpty()) {
            registerInBackground();
        } else {
            Log.i(TAG, "Already registered for GCM: " + regid);
        }
    } else {
        Log.i(TAG, "No valid Google Play Services APK found.");
    }
}
 
Example 10
Source File: GcmIntentService.java    From MobileShoppingAssistant-sample with Apache License 2.0 4 votes vote down vote up
@Override
protected final void onHandleIntent(final 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 unpacking 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.
         */
        switch (messageType) {
            case GoogleCloudMessaging.MESSAGE_TYPE_DELETED:
                sendNotification("Deleted messages on server: "
                        + extras.toString());
                // If it's a regular GCM message, do some work.
                break;
            case GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE:
                if (intent.getStringExtra("NotificationKind")
                        .equals("PriceCheckLowerPrices1")) {
                    final String message
                            = getUserMessageForPriceCheckLowerPricesNotif(
                            intent);

                    Handler h = new Handler(Looper.getMainLooper());
                    h.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast toast = Toast
                                    .makeText(getApplicationContext(),
                                            message,
                                            Toast.LENGTH_LONG);
                            toast.show();
                        }
                    });
                }
                break;
            case GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR:
            default:
                sendNotification("Send error: " + extras.toString());
                break;
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}
 
Example 11
Source File: GCMRegistrar.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public GCMRegistrar(Context context) {
    this.mContext = context;
    gcm = GoogleCloudMessaging.getInstance(context);
}
 
Example 12
Source File: MainActivity.java    From MobileShoppingAssistant-sample with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes the activity content, binds relevant widgets, sets up
 * geo-location retrieval, registers with Google Cloud Messaging (GCM)
 * and starts asynchronously retrieving the list of nearby places.
 */
@Override
protected final void onCreate(final Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // Handle to the GAE endpoints in the backend
    shoppingAssistantAPI = CloudEndpointBuilderHelper.getEndpoints();

    context = getApplicationContext();

    new CheckInTask().execute();

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.activity_main);

    placesList = (ListView) findViewById(R.id.PlacesList);
    placesListLabel = (TextView) findViewById(R.id.PlacesListLabel);
    placesList.setOnItemClickListener(placesListClickListener);

    geoLocationHelper.startRetrievingLocation(this);

    // Check device for Play Services APK. If check succeeds, proceed
    // with GCM registration.
    if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(this);
        regId = getRegistrationId(context);

        if (regId.isEmpty()) {
            Log.i(TAG, "Not registered with GCM.");

            // Register GCM id in the background
            new GcmAsyncRegister().execute();

        }
    } else {
        Log.i(TAG, "No valid Google Play Services APK found.");
    }

    // start retrieving the list of nearby places
    new ListOfPlacesAsyncRetriever()
            .execute(geoLocationHelper.getCurrentLocation());
}
 
Example 13
Source File: MainActivity.java    From effective_android_sample with Apache License 2.0 4 votes vote down vote up
@Override
public void onClick(View v) {
    if(v.getId() == R.id.btn_regist){
        if (regid.equals("")) {
            // GCM登録用AsyncTaskの実行
            mRegisterTask = new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    if (gcm == null) {
                        // インスタンスがなければ取得する
                        gcm = GoogleCloudMessaging.getInstance(context);
                    }
                    try {
                        // GCMサーバーへ登録する
                        regid = gcm.register(CommonUtilities.SENDER_ID);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    // レジストレーションIDを自分のサーバーへ送信する
                    // レジストレーションIDをつかえば、アプリケーションにGCMメッセージを送信できるようになります
                    Log.i(TAG,"送信対象のレジストレーションID: " + regid);
                    register(regid);
                    
                    // レジストレーションIDを端末に保存
                    storeRegistrationId(context, regid);
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    mRegisterTask = null;
                }
            };
            mRegisterTask.execute(null, null, null);
        }
    }else if(v.getId() == R.id.btn_unregist){
        //GCMサーバーから登録を解除するAsyncTaskの実行
        mRegisterTask = new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                if (gcm == null) {
                    // インスタンスがなければ取得する
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                try {
                    // GCMサーバーの登録を解除する
                    gcm.unregister();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // レジストレーションIDを自分のサーバーでも削除する
                unregister(regid);
                
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                mRegisterTask = null;
            }

        };
        mRegisterTask.execute(null, null, null);
    }
}
 
Example 14
Source File: GcmBroadcastReceiver.java    From zulip-android with Apache License 2.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    // handle cancel notification action on uploads
    final String action = intent.getAction();
    if (Constants.CANCEL.equals(action)) {
        int notifId = intent.getIntExtra("id", 0);
        try {
            ZulipApp.get().getZulipActivity().cancelRequest(notifId);
        } catch (NullPointerException e) {
            ZLog.log("onReceive: app destroyed but notification visible");
            return;
        }
    }

    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
    // 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)) {
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
                .equals(messageType)) {
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
                .equals(messageType)) {

            Log.i(TAG, "Received: " + extras.toString());
            if (extras.getString("event").equals("message")) {
                Intent broadcast = new Intent(getGCMReceiverAction(context.getApplicationContext()));
                broadcast.putExtras(extras);
                context.sendOrderedBroadcast(broadcast, null);
            }
        }
    }

    setResultCode(Activity.RESULT_OK);
}
 
Example 15
Source File: MainActivity.java    From odm with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected String doInBackground(String... arg0) {
	Logd(TAG, "Checking update alarm.");
	UpdateAlarm updateAlarm = new UpdateAlarm();
	updateAlarm.SetAlarmContext(context);
	if (version.equals("true")) {
		Logd(TAG, "Good to start update alarm.");
		updateAlarm.SetAlarm(context);
	} else {
		Logd(TAG, "Shutting down update alarm.");
		updateAlarm.CancelAlarm(context);
	}
	Logd(TAG, "Checking location alarm.");
	LocationAlarm locationAlarm = new LocationAlarm();
	locationAlarm.SetAlarmContext(context);
	locationAlarm.SetInterval(interval);
	if (!interval.equals("0")) {
		Logd(TAG, "Good to start location alarm.");
		locationAlarm.SetAlarm(context);
	} else {
		Logd(TAG, "Shutting down location alarm.");
		locationAlarm.CancelAlarm(context);
	}
	try {
		Logd(TAG, "Checking if GCM is null.");
		if (gcm == null) {
			Logd(TAG, "It is, initializing.");
			gcm = GoogleCloudMessaging.getInstance(context);
		}
		Logd(TAG, "Registering.");
		regId = gcm.register(getVAR("SENDER_ID"));
		Logd(TAG, "Device registered, registration ID=" + regId);
		SharedPreferences mPrefs = getSharedPreferences("usersettings", 0);
		SharedPreferences.Editor mEditor = mPrefs.edit();
		mEditor.putString("REG_ID", regId).commit();
		// We are never setting the application REG_ID, but it shouldn't matter, as the service will refresh
		Logd(TAG, "Executing server registration.");
		ServerUtilities.register(context, regId);
	} catch (IOException ex) {
		Logd(TAG, "Error :" + ex.getMessage());
	}
	return null;
}
 
Example 16
Source File: GcmActivity.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
private static synchronized String sendMessageNow(String identity, String action, String payload, byte[] bpayload) {

        Log.i(TAG, "Sendmessage called: " + identity + " " + action + " " + payload);
        String msg;
        try {

            if (xdrip.getAppContext() == null) {
                Log.e(TAG, "mContext is null cannot sendMessage");
                return "";
            }

            if (identity == null) {
                Log.e(TAG, "identity is null cannot sendMessage");
                return "";
            }

            if (overHeated()) {
                UserError.Log.e(TAG, "Cannot send message due to cool down period: " + action + " till: " + JoH.dateTimeText(cool_down_till));
                return "";
            }

            final Bundle data = new Bundle();
            data.putString("action", action);
            data.putString("identity", identity);

            if (action.equals("sensorupdate")) {
                final String ce_payload = CipherUtils.compressEncryptString(payload);
                Log.i(TAG, "sensor length CipherUtils.encryptBytes ce_payload length: " + ce_payload.length());
                data.putString("payload", ce_payload);
                if (d) Log.d(TAG, "sending data len " + ce_payload.length() + " " + ce_payload);
            } else {
                if ((bpayload != null) && (bpayload.length > 0)) {
                    data.putString("payload", CipherUtils.encryptBytesToString(Bytes.concat(bpayload, JoH.bchecksum(bpayload)))); // don't double sum
                } else if (payload.length() > 0) {
                    data.putString("payload", CipherUtils.encryptString(payload));
                } else {
                    data.putString("payload", "");
                }
            }

            if (gcm_queue.size() < MAX_QUEUE_SIZE) {
                if (shouldAddQueue(data)) {
                    gcm_queue.add(new GCM_data(data));
                }
            } else {
                Log.e(TAG, "Queue size exceeded");
                Home.toaststaticnext("Maximum Sync Queue size Exceeded!");
            }
            final GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(xdrip.getAppContext());
            if (token == null) {
                Log.e(TAG, "GCM token is null - cannot sendMessage");
                return "";
            }
            String messageid = Integer.toString(msgId.incrementAndGet());
            gcm.send(senderid + "@gcm.googleapis.com", messageid, data);
            if (last_ack == -1) last_ack = JoH.tsl();
            last_send_previous = last_send;
            last_send = JoH.tsl();
            msg = "Sent message OK " + messageid;
            DesertSync.fromGCM(data);
        } catch (IOException ex) {
            msg = "Error :" + ex.getMessage();
        }
        Log.d(TAG, "Return msg in SendMessage: " + msg);
        return msg;
    }
 
Example 17
Source File: GCMIntentService.java    From buddycloud-android with Apache License 2.0 4 votes vote down vote up
@Override
protected void onHandleIntent(Intent remoteIntent) {
	
	Logger.info(TAG, "GCM reveived " + remoteIntent.toString());
       GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
       String messageType = gcm.getMessageType(remoteIntent);
       
	Bundle extras = remoteIntent.getExtras();
	if (!extras.isEmpty())
	{
		if (GoogleCloudMessaging.
                   MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
			Logger.info(TAG, "Send error: " + extras.toString());
           } else if (GoogleCloudMessaging.
                   MESSAGE_TYPE_DELETED.equals(messageType)) {
           	Logger.info(TAG, "Deleted messages on server: " + extras.toString());
           } else if (GoogleCloudMessaging.
                   MESSAGE_TYPE_MESSAGE.equals(messageType)) {
           	
           	// If it's a regular GCM message, do some work.
       		final Context context = ApplicationManager.getAppContext();
       		final SyncModel syncModel = SyncModel.getInstance();
       		SyncModel.getInstance().syncNoSummary(context, new ModelCallbackImpl<Void>(){
       			@Override
       			public void success(Void response) {
       				syncModel.fill(context, new ModelCallbackImpl<Void>());
       			}
       			
       			@Override
       			public void error(Throwable throwable) {
       				success(null);
       			}
       		});
       		
       		GCMEvent event = GCMEvent.valueOf(remoteIntent.getStringExtra("event"));
       		GCMNotificationListener notificationListener = createNotificationListener(context, event);
       		if (notificationListener != null) {
       			notificationListener.onMessage(event, context, remoteIntent);
       		}
           }
	}

	 // Release the wake lock provided by the WakefulBroadcastReceiver.
       GCMBroadcastReceiver.completeWakefulIntent(remoteIntent);
}
 
Example 18
Source File: TapchatModule.java    From tapchat-android with Apache License 2.0 4 votes vote down vote up
@Provides @Singleton public GoogleCloudMessaging provideGCM() {
    return GoogleCloudMessaging.getInstance(mAppContext);
}
 
Example 19
Source File: GCMRegistrar.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public GCMRegistrar(Context context) {
    this.mContext = context;
    gcm = GoogleCloudMessaging.getInstance(context);
}
 
Example 20
Source File: SmsIntentService.java    From android-sms-gateway with Apache License 2.0 4 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))
        {
            String number = extras.getString("number");
            String message = extras.getString("message");
            if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(message))
            {
                try
                {
                    if (!number.startsWith("+"))
                    {
                        number = "+" + number;
                    }
                    SmsManager smsManager = SmsManager.getDefault();
                    ArrayList<String> parts = smsManager.divideMessage(message);
                    if (parts.size() > 1)
                    {
                        smsManager.sendMultipartTextMessage(number, null, parts, null, null);
                    }
                    else
                    {
                        smsManager.sendTextMessage(number, null, message, null, null);
                    }

                    String result = number + ": " + message;
                    Log.i(TAG, result);

                    sendNotification(result);

                    ContentValues values = new ContentValues();
                    values.put("address", number);
                    values.put("body", message);
                    getApplicationContext().getContentResolver()
                                           .insert(Uri.parse("content://sms/sent"), values);
                }
                catch (Exception ex)
                {
                    Log.e(TAG, ex.toString());
                }
            }
        }
    }
    SmsBroadcastReceiver.completeWakefulIntent(intent);
}